how to get machines mac address

后端 未结 3 1845
我在风中等你
我在风中等你 2021-02-06 16:57

I want get machines\' MAC address..but below written code only display the MAC address when Internet is connected to my machine other it will return null... I am using windows 7

3条回答
  •  我在风中等你
    2021-02-06 17:59

    The problem is probably caused by the fact that when your machine isn't connected to the Internet, your network card doesn't have an assigned IP address. And you are trying to look up the network interface by an IP address.

    I suggest you to enumerate all network interfaces instead, and pick the one you need:

    import java.net.*;
    import java.util.*;
    
    public class App {
    
        protected static String formatMac(byte[] mac) {
            if (mac == null)
                return "UNKNOWN";
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mac.length; i++) {
                sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
            }
            return sb.toString();
        }
    
       public static void main(String[] args) throws Exception {
           for(Enumeration e
                        = NetworkInterface.getNetworkInterfaces();
                   e.hasMoreElements(); )
           {
               NetworkInterface ni = e.nextElement();
               System.out.println(ni.getName() + " - " + formatMac(ni.getHardwareAddress()));
           }
       }
    }
    

    This should solve the problem and work without any Internet connection.

提交回复
热议问题