Java Mac Address Get getMACAddress(String interfaceName)

Here you can find the source of getMACAddress(String interfaceName)

Description

Returns MAC address of the given interface name.

License

Apache License

Parameter

Parameter Description
interfaceName eth0, wlan0 or NULL=use first interface

Return

mac address or empty string

Declaration

public static String getMACAddress(String interfaceName) 

Method Source Code

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

import java.net.*;
import java.util.*;

public class Main {
    /**//from  w  w  w  .j  a v  a2  s.  co  m
     * Returns MAC address of the given interface name.
     * @param interfaceName eth0, wlan0 or NULL=use first interface 
     * @return  mac address or empty string
     */
    public static String getMACAddress(String interfaceName) {
        try {
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface intf : interfaces) {
                if (interfaceName != null) {
                    if (!intf.getName().equalsIgnoreCase(interfaceName))
                        continue;
                }
                byte[] mac = intf.getHardwareAddress();
                if (mac == null)
                    return "";
                StringBuilder buf = new StringBuilder();
                for (int idx = 0; idx < mac.length; idx++)
                    buf.append(String.format("%02X:", mac[idx]));
                if (buf.length() > 0)
                    buf.deleteCharAt(buf.length() - 1);
                return buf.toString();
            }
        } catch (Exception ex) {
        } // for now eat exceptions
        return "";
        /*try {
        // this is so Linux hack
        return loadFileAsString("/sys/class/net/" +interfaceName + "/address").toUpperCase().trim();
        } catch (IOException ex) {
        return null;
        }*/
    }
}

Related

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