Java Mac Address Get getMacAddressString()

Here you can find the source of getMacAddressString()

Description

get Mac Address String

License

Apache License

Declaration

public static String getMacAddressString() 

Method Source Code

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

import java.net.NetworkInterface;
import java.net.SocketException;

import java.util.Enumeration;

public class Main {
    public static byte[] macAddress = null;

    public static String getMacAddressString() {
        byte[] macByte = getMacAddress();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < macByte.length; i++) {
            sb.append(String.format("%02X%s", macByte[i], (i < macByte.length - 1) ? ":" : ""));
        }/*  w w w.j a v a2  s  . co m*/
        return sb.toString();
    }

    public static byte[] getMacAddress() {
        try {
            if (macAddress != null && macAddress.length > 0)
                return macAddress;
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface network = networkInterfaces.nextElement();
                byte[] nextInterface = network.getHardwareAddress();
                if (nextInterface != null && nextInterface.length > 0) {
                    macAddress = nextInterface;
                    return nextInterface;
                }
            }
            return new byte[15];
        } catch (SocketException e) {
            e.printStackTrace();
            return null;
        }
    }
}

Related

  1. getMacAddress(String host)
  2. getMACAddress(String interfaceName)
  3. getMacAddress(String separator)
  4. getMacAddressBytes()
  5. getMacAddresses()
  6. getMacAddrs()
  7. GetMachineAddress()