0

I'm trying to get the MAC address of my PC without connecting to the internet, I used this code

InetAddress ip;
try {
    ip = InetAddress.getLocalHost(); 

    NetworkInterface network = NetworkInterface.getByInetAddress(ip);

    byte[] mac = network.getHardwareAddress();

    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 | SocketException e) {
}

it works when my computer is connected to internet, but when i go offline it doesn't.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Abdalltif Basher
  • 617
  • 7
  • 19
  • possible duplicate of [how to get machines mac address](http://stackoverflow.com/questions/11884696/how-to-get-machines-mac-address) – kevcodez Jul 04 '15 at 15:52
  • please refer to the link http://stackoverflow.com/questions/6164167/get-mac-address-on-local-machine-with-java hope this will help – user3134614 Jul 04 '15 at 16:02

1 Answers1

1

Here is the code for getting mac address for your PC even if it is not connected to internet:

public static void main(String[] args) throws SocketException {
final Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
    while (e.hasMoreElements()) {
        final byte [] mac = e.nextElement().getHardwareAddress();
        if (mac != null) {
            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());
        }
    }
}

Note: Many machines have multiple Mac Addresses as well. So this might return you multiple Mac Addresses

nijm
  • 2,158
  • 12
  • 28
Ashit Shah
  • 91
  • 1
  • 1