Example usage for java.net NetworkInterface getHardwareAddress

List of usage examples for java.net NetworkInterface getHardwareAddress

Introduction

In this page you can find the example usage for java.net NetworkInterface getHardwareAddress.

Prototype

public byte[] getHardwareAddress() throws SocketException 

Source Link

Document

Returns the hardware address (usually MAC) of the interface if it has one and if it can be accessed given the current privileges.

Usage

From source file:com.frostwire.util.VPNs.java

public static void printNetworkInterfaces() {
    try {//w  w  w  .  j  av a 2  s .  c  om
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface iface = networkInterfaces.nextElement();
            System.out.println(iface.getIndex() + ":" + iface.getDisplayName() + ":" + "virtual="
                    + iface.isVirtual() + ":" + "mtu=" + iface.getMTU() + ":mac="
                    + (iface.getHardwareAddress() != null
                            ? "0x" + ByteUtils.encodeHex(iface.getHardwareAddress())
                            : "n/a"));
        }
    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.tinymediamanager.core.License.java

/**
 * returns ALL found MAC address of this instance
 * /*  w  w w.j a  v  a 2 s.  co  m*/
 * @return MAC or empty string
 */
private static List<String> getAllMacAddresses() {
    List<String> m = new ArrayList<>();
    m.add(UNKNOWN_MAC); // lic generated with empty mac, but java cannot handle this :/ use fake mac for further checks
    try {
        for (Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); e.hasMoreElements();) {
            NetworkInterface ni = e.nextElement();
            String macAddress = formatMac(ni.getHardwareAddress());
            if (macAddress != null && !macAddress.isEmpty()) {
                m.add(macAddress);
            }
        }
    } catch (Exception e) {
        LOGGER.warn("Error getting MAC of all interfaces");
    }
    return m;
}

From source file:license.rsa.WakeRSA.java

/**
 * ?mac/* ww w . j  a  va  2 s . c  o m*/
 * @param sb
 * @throws Exception
 */
private static void mac(StringBuilder sb) throws Exception {
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    int i = 12;
    Base64 base64 = new Base64();
    for (NetworkInterface ni : Collections.list(interfaces))
        if (ni.getName().substring(0, 1).equalsIgnoreCase("e")) {
            sb.append(String.valueOf(i)).append('=').append(ni.getName()).append('\n');
            i++;
            byte[] mac = ni.getHardwareAddress();
            sb.append(String.valueOf(i)).append('=').append(base64.encodeAsString(mac)).append('\n');
            i++;
        }
}

From source file:ezbake.services.graph.archive.TransactionIdGenerator.java

private static byte[] getMacAddress(String interfaceName) {
    Preconditions.checkArgument(interfaceName != null, "Interface name cannot be null.");
    try {/*from  w ww  .  jav  a2 s  .  c  o m*/
        NetworkInterface network = NetworkInterface.getByName(interfaceName);
        if (network == null) {
            throw new IllegalStateException("Can't get interface: " + interfaceName);
        }
        byte[] mac = network.getHardwareAddress();
        return (mac != null) ? mac : MAC_ADDRESS_DEFAULT;
    } catch (SocketException ex) {
        throw new IllegalStateException("Can't get MAC address: " + interfaceName);
    }
}

From source file:com.ikon.servlet.ValidateLicenseServlet.java

/**
 * get MacId of the server./*from  w w w .j av  a 2  s. c o  m*/
 * @return
 * @throws IOException
 */
static String getMacAddress() throws IOException {
    InetAddress inetAddress;
    NetworkInterface networkInterface;
    StringBuilder sb = new StringBuilder();

    try {
        inetAddress = InetAddress.getLocalHost();
        networkInterface = NetworkInterface.getByInetAddress(inetAddress);
        byte[] mac = networkInterface.getHardwareAddress();

        for (int i = 0; i < mac.length; i++) {
            sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
        }
    } catch (UnknownHostException e) {
        throw new IOException("Unknown Host. Please try again later.");
    } catch (SocketException e) {
        throw new IOException("Could not connect to the socket. Please try again later.");
    }
    return sb.toString();
}

From source file:com.jiangyifen.ec2.globaldata.license.LicenseManager.java

/**
 * "xx-xx-xx-xx-xx-xx"??MAC?//  w  w w .  ja v  a 2s .co m
 * 
 * @return
 * @throws Exception
 */
private static List<String> getMacAddressList() {
    List<String> macAddressList = new ArrayList<String>();
    try {
        Enumeration<NetworkInterface> ni = NetworkInterface.getNetworkInterfaces();

        while (ni.hasMoreElements()) {
            NetworkInterface netI = ni.nextElement();

            byte[] bytes = netI.getHardwareAddress();
            if (netI.isUp() && netI != null && bytes != null && bytes.length == 6) {
                StringBuffer sb = new StringBuffer();
                for (byte b : bytes) {
                    // 11110000????4?
                    sb.append(Integer.toHexString((b & 240) >> 4));
                    // 00001111????4?
                    sb.append(Integer.toHexString(b & 15));
                    sb.append("-");
                }
                sb.deleteCharAt(sb.length() - 1);
                macAddressList.add(sb.toString().toLowerCase());
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return macAddressList;
}

From source file:com.ghgande.j2mod.modbus.utils.TestUtils.java

/**
 * Returns the last adapter it finds that is not a loopback
 *
 * @return Adapter to use/*from w w  w .java  2  s.c o  m*/
 */
public static List<NetworkInterface> getNetworkAdapters() {
    List<NetworkInterface> returnValue = new ArrayList<NetworkInterface>();
    try {

        // Loop round all the adapters

        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {

            // Get the MAC address if it exists

            NetworkInterface network = networkInterfaces.nextElement();
            byte[] mac = network.getHardwareAddress();
            if (mac != null && mac.length > 0 && network.getInterfaceAddresses() != null) {
                returnValue.add(network);
                logger.debug("Current MAC address : {} ({})", returnValue, network.getDisplayName());
            }
        }
    } catch (Exception e) {
        logger.error("Cannot determine the local MAC address - {}", e.getMessage());
    }
    return returnValue;
}

From source file:org.cocos2dx.lib.CCUtils.java

public static String getMacAddress() {
    String mac = "";
    Context ctx = Cocos2dxActivity.getContext();

    // first, try to get mac from wifi manager
    if (ctx.checkCallingPermission(permission.ACCESS_WIFI_STATE) == PackageManager.PERMISSION_GRANTED) {
        WifiManager wifi = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        mac = info.getMacAddress();/*  ww w  .jav a2 s  .c  o m*/
    }

    // if failed, try from network interface api
    if (TextUtils.isEmpty(mac)) {
        if (Build.VERSION.SDK_INT >= 9) {
            try {
                NetworkInterface ne = NetworkInterface
                        .getByInetAddress(InetAddress.getByName(getLocalIpAddress()));
                byte[] b = ne.getHardwareAddress();
                mac = byte2Hex(b);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // if failed, use fake
    if (TextUtils.isEmpty(mac)) {
        mac = "00:00:00:00:00:00";
    }

    // return
    return mac;
}

From source file:camp.pixels.signage.util.NetworkInterfaces.java

public static String getMACAddress(String interfaceName) {
    try {/*from   w  w w  .j a  va2 s  .c  om*/
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            if (interfaceName != null) {
                if (!intf.getName().equalsIgnoreCase(interfaceName))
                    continue;
            }
            if (!VALID_INTERFACES.contains(intf.getName()))
                continue;
            byte[] mac = intf.getHardwareAddress();
            if (mac == null)
                continue;//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);
            //Log.d("getMACAddress", intf.getName());
            //Log.d("getMACAddress", buf.toString());
            return buf.toString();
        }
    } catch (SocketException ex) {
    }
    return "";
}

From source file:com.DPFaragir.DPFUtils.java

public static String getMACAddress(String interfaceName) {
    try {//w w w  .j av a 2s  .c om
        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;
    }*/
}