Java Mac Address Get getMacAddress()

Here you can find the source of getMacAddress()

Description

Returns the MAC address of the first network interface that is found.

License

Apache License

Return

MAC address of null if no network address was found.

Declaration

public static String getMacAddress() 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.net.NetworkInterface;
import java.util.Collections;

public class Main {
    /**/*from  w  ww  . ja  va  2  s .  c  o  m*/
     * Returns the MAC address of the first network interface that is found.
     * 
     * @return   MAC address of <tt>null</tt> if no network address was found.
     */
    public static String getMacAddress() {
        try {
            String mac = null;

            for (NetworkInterface ni : Collections.list(NetworkInterface.getNetworkInterfaces())) {
                if (ni.getHardwareAddress() != null) {
                    byte[] hwAddr = ni.getHardwareAddress();
                    if (hwAddr.length > 0) {
                        mac = "";
                        for (int i = 0; i < hwAddr.length; i++) {
                            mac += String.format("%02X%s", hwAddr[i], (i < hwAddr.length - 1) ? ":" : "");
                        }
                        break;
                    }
                }
            }

            return mac;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

Related

  1. getMacAddress()
  2. getMACAddress()
  3. getMacAddress()
  4. getMACAddress()
  5. getMacAddress()
  6. getMacAddress()
  7. getMacAddress()
  8. getMACAddress()
  9. getMacAddress()