Sunday, April 17, 2016

Get my MAC address using NetworkInterface

Java example to get MAC address using NetworkInterface:



package javamyip;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaMyIP {

    public static void main(String[] args) {
        displayMyIP();
    }
    
    static void displayMyIP(){
        Enumeration<NetworkInterface> nets;
        try {
            nets = NetworkInterface.getNetworkInterfaces();
            for (NetworkInterface netint : Collections.list(nets)){
                System.out.printf(netint.getDisplayName() +"\n");
                Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
                for (InetAddress inetAddress : Collections.list(inetAddresses)) {
                    System.out.printf("InetAddress: %s\n", inetAddress);
                }
                
                byte[] mac = netint.getHardwareAddress();
                if(mac != null){
                    StringBuilder macAddr = new StringBuilder();
                    for (int i = 0; i < mac.length; i++) {
                        macAddr.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? ":" : "")); 
                    }
                    System.out.printf("Hardware address (MAC): [%s]\n", macAddr.toString());
                }
                
                System.out.printf("\n");
            }
        } catch (SocketException ex) {
            Logger.getLogger(JavaMyIP.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

No comments:

Post a Comment