Java Mac Address Get getMacAddress()

Here you can find the source of getMacAddress()

Description

get Mac Address

License

Open Source License

Declaration

public static String getMacAddress() throws Exception 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;

import java.util.Enumeration;

public class Main {
    public static String getMacAddress() throws Exception {
        NetworkInterface network = NetworkInterface.getByInetAddress(getLocalAddress());

        byte[] mac = network.getHardwareAddress();

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < mac.length; i++) {
            sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
        }/*from  ww w  . ja v  a  2s .  c  o  m*/

        return sb.toString();
    }

    public static InetAddress getLocalAddress() throws SocketException {
        Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
        while (ifaces.hasMoreElements()) {
            NetworkInterface iface = ifaces.nextElement();
            Enumeration<InetAddress> addresses = iface.getInetAddresses();

            while (addresses.hasMoreElements()) {
                InetAddress addr = addresses.nextElement();
                if (addr instanceof Inet4Address && !addr.isLoopbackAddress()) {
                    return addr;
                }
            }
        }

        return null;
    }
}

Related

  1. getMACAddress()
  2. getMacAddress()
  3. getMacAddress()
  4. getMacAddress()
  5. getMacAddress()
  6. getMacAddress(String host)
  7. getMACAddress(String interfaceName)
  8. getMacAddress(String separator)
  9. getMacAddressBytes()