how to get machines mac address

后端 未结 3 1887
我在风中等你
我在风中等你 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条回答
  •  Happy的楠姐
    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();
        }
    
    }
    

提交回复
热议问题