Search code examples
javawindowsmac-addressserial-number

How to get mac address from integrated network adapter


Many motherboards have an integrated network adapter. I need to get mac address from this device if exists. From Network adapter:

private void getMacFromInetAddress(){
    try {

            Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
            while (networks.hasMoreElements()) {
                NetworkInterface network = networks.nextElement();
                byte[] mac = network.getHardwareAddress();

                if (mac != null) {
                    System.out.print("Current MAC address : ");

                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < mac.length; i++) {
                        sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
                    }
                }
           }
        } catch (UnknownHostException | SocketException e) {
            System.out.println(e.getLocalizedMessage());
        }
}

how to get specify the name of a integrated network adapter from this code?


Solution

  • InetAddress ip = InetAddress.getLocalHost();
    System.out.println("Current IP address : " + ip.getHostAddress());
    
    NetworkInterface network = NetworkInterface.getByInetAddress(ip);
    
    byte[] mac = network.getHardwareAddress();
    
    System.out.print("Current MAC address : ");
    
    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());
    

    and to get the hardware info u can use wmic commands like wmic cpu get ProcessorId

     Process p = Runtime.getRuntime().exec("wmic cpu get ProcessorId");
                String procesSerial=
                        new BufferedReader
                                (new InputStreamReader(p.getInputStream())).[ReadSecondLine];
    

    and bios

    wmic bios get SerialNumber

     Process p = Runtime.getRuntime().exec("wmic bios get SerialNumber");