Java – Get MAC Address

Since JDK 1.6, Java developers are able to access network card detail via NetworkInterface class. In this example, we show you how to get the localhost MAC address in Java.

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

public class MacAddress {

    public static void main(String[] args) {

        InetAddress ip;

        try {

            ip = InetAddress.getLocalHost();
            System.out.println("Current IP address : " + ip.getHostAddress());

            NetworkInterface network = NetworkInterface.getByInetAddress(ip);
            byte[] mac = network.getHardwareAddress();

            System.out.print("Current MAC address : ");

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mac.length; i++) {
                sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
            }
            System.out.println(sb.toString());

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (SocketException e){
            e.printStackTrace();
        }

    }

}

Output:

Current IP address : 192.168.1.22
Current MAC address : 00-26-B9-9B-61-BF

Note: The NetworkInterfaceNetworkInterface.getHardwareAddress() method is only allowed to access localhost MAC address, not remote host MAC address.

Java – Get List of Files from FTP Server

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.io.FileUtils;
import java.io.IOException;

public class Main {

	public static void main(String[] args) {
		FTPClient client = new FTPClient();

		client.connect("ftp.domain.com");
		client.login("admin", "secret");

		String[] names = client.listNames();
		for (String name : names) {
			System.out.println("Name = " + name);
		}

		FTPFile[] ftpFiles = client.listFiles();
		for (FTPFile ftpFile : ftpFiles) {
			// Check if FTPFile is a regular file
			if (ftpFile.getType() == FTPFile.FILE_TYPE) {
				System.out.println("FTPFile: " + ftpFile.getName() + "; "
						+ FileUtils.byteCountToDisplaySize(ftpFile.getSize()));
			}
		}
		client.logout();
		client.disconnect();
	}

}

Java – Upload File to FTP Server

import org.apache.commons.net.ftp.FTPClient;
import java.io.FileInputStream;
import java.io.IOException;

public class Main {

	public static void main(String[] args) {
		FTPClient client = new FTPClient();
		FileInputStream fis = null;

		client.connect("ftp.domain.com");
		client.login("admin", "secret");

		String filename = "Touch.dat";
		fis = new FileInputStream(filename);
		client.storeFile(filename, fis);
		client.logout();
		fis.close();
	}

}

Page 1 of 41234