Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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.



This post first appeared on Javac, please read the originial post: here

Share the post

Java – Get MAC Address

×

Subscribe to Javac

Get updates delivered right to your inbox!

Thank you for your subscription

×