Java Mac Address Get getMacAddress()

Here you can find the source of getMacAddress()

Description

get Mac Address

License

Open Source License

Return

the fetched MAC address.

Declaration

public static String getMacAddress() 

Method Source Code

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

import java.net.InetAddress;
import java.net.NetworkInterface;

public class Main {
    private static final String OS_NAME = System.getProperty("os.name");
    /**/*  w w w  .j  ava  2s . c  o  m*/
     * The MAC address.
     */
    private static String macAddress;

    /**
     * @return the fetched MAC address.
     */
    public static String getMacAddress() {
        if (macAddress == null) {
            try {
                fetchMacAddress();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (macAddress == null) {
                macAddress = "unknown";
            }
        }
        return macAddress;
    }

    /**
     * Fetch the MAC address.
     * @throws UnknownHostException
     * @throws SocketException
     */
    private static void fetchMacAddress() throws Exception {
        InetAddress ip = InetAddress.getLocalHost();
        NetworkInterface network = NetworkInterface.getByInetAddress(ip);
        if (network == null) {
            network = isLinux() ? NetworkInterface.getByName("eth0") : null;
        }
        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) ? "-" : ""));
        }
        macAddress = sb.toString();
    }

    public static boolean isLinux() {
        return OS_NAME.toLowerCase().contains("linux");
    }
}

Related

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