Search code examples
javamac-address

Get the correct non-virtual MAC address in java


I am programming a virtual router. And my first task is to build an Ethernet Frame. I am currently trying to get the MAC source address. I have code that gets all the MAC addresses being used on my machine but I have a virtualbox host network so the code is grabbing this MAC address as well. I am having trouble determining programmatically which MAC address I should be using for my Ethernet Frame. This is my current code

private byte[] grabMACAddress(){
    try{ 
        InetAddress[] addresses = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());

        for(int i = 0; i < addresses.length; i++){
            NetworkInterface ni = NetworkInterface.getByInetAddress(addresses[i]);


            mac = ni.getHardwareAddress();
            if (mac != null){
                for(int j=0; j < mac.length; j++) {
                                        String part = String.format("%02X%s", mac[j], (j < mac.length - (1)) ? "" : "");
                                        s += part;
                }
                System.out.println();
            }
            else{
                System.out.println("Address doesn't exist or is not accessible.");
            }

        }
    }
    catch(IOException e){

    }
            System.out.println(s);
            return mac;
}

Solution

  • Support for isolating multiple network interfaces is OS-specific, so no built-in support is available in Java.

    A simple way to find your 'main' IP address is to connect to a public server, and inspect the 'client address' used for the connection:

        Socket socket= new Socket();
        SocketAddress endpoint= new InetSocketAddress("www.google.com", 80);
        socket.connect(endpoint);
        InetAddress localAddress = socket.getLocalAddress();
        socket.close();
        System.out.println(localAddress.getHostAddress());
        NetworkInterface ni = NetworkInterface.getByInetAddress(localAddress);
        byte[] mac = ni.getHardwareAddress();
        StringBuilder s=new StringBuilder();
        if (mac != null){
            for(int j=0; j < mac.length; j++) {
                                    String part = String.format("%02X%s", mac[j], (j < mac.length - (1)) ? "" : "");
                                    s.append(part);
            }
    
            System.out.println("MAC:" + s.toString());
        }
        else{
            System.out.println("Address doesn't exist or is not accessible.");
        }
    

    Beyond this, you may want to look into low-level JNI-based libraries for handling low-level network protocols, or even looking up routing tables. Something like http://jnetpcap.com/ may be interesting for you.

    HTH