how to get machines mac address

后端 未结 3 1846
我在风中等你
我在风中等你 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:40

    Try this it should work in both Linux and windows

    public static void main(String[] args) {
    
        String command = "/sbin/ifconfig";
    
        String sOsName = System.getProperty("os.name");
        if (sOsName.startsWith("Windows")) {
            command = "ipconfig";
        } else {
    
            if ((sOsName.startsWith("Linux")) || (sOsName.startsWith("Mac"))
                    || (sOsName.startsWith("HP-UX"))) {
                command = "/sbin/ifconfig";
            } else {
                System.out.println("The current operating system '" + sOsName
                        + "' is not supported.");
            }
        }
    
        Pattern p = Pattern
                .compile("([a-fA-F0-9]{1,2}(-|:)){5}[a-fA-F0-9]{1,2}");
        try {
            Process pa = Runtime.getRuntime().exec(command);
            pa.waitFor();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    pa.getInputStream()));
    
            String line;
            Matcher m;
            while ((line = reader.readLine()) != null) {
    
                m = p.matcher(line);
    
                if (!m.find())
                    continue;
                line = m.group();
                break;
    
            }
            System.out.println(line);
        } catch (Exception e) {
            e.printStackTrace();
        }
    
    }
    
    0 讨论(0)
  • 2021-02-06 17:47

    Seems like you are trying to get the MAC address by IP address. An IP address exists only when you are connected successfully to the Internet. Otherwise, it will be null, as you state.

    Try this: NetworkInterface.getHardwareAddress().

    If you want the MAC address of all network interfaces on your computer, try this: NetworkInterface.getNetworkInterfaces().


    EDIT: After reviewing the code again, I realize that you have my suggestion implemented. However, you are only trying to obtain the MAC address if you have a valid IP. You will not have a valid IP if are not connected to the Internet.

       public static void main(String[] args) 
       { 
           NetworkInterface network;
           byte[] mac = network.getHardwareAddress();  
           System.out.print("The mac address is : ");  
    
           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());  
       } 
    
    0 讨论(0)
  • 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<NetworkInterface> 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.

    0 讨论(0)
提交回复
热议问题