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:de.pawlidi.openaletheia.utils.AletheiaUtils.java

/**
 * Read java networt mac adress//from   w  w  w  .j a v  a 2s  . c o  m
 * 
 * @return
 */
public static String getJavaNetMacAddress() {
    String javaMacAdress = null;
    try {
        InetAddress ip = InetAddress.getLocalHost();

        if (ip == null) {
            return null;
        }

        NetworkInterface network = NetworkInterface.getByInetAddress(ip);

        if (network == null) {
            return null;
        }

        byte[] mac = network.getHardwareAddress();

        javaMacAdress = Converter.hexToString(mac);

    } catch (UnknownHostException e) {
        // ignore exception
    } catch (SocketException e) {
        // ignore exception
    }
    return javaMacAdress;
}

From source file:com.rincliu.library.util.RLNetUtil.java

/**
 * Returns MAC address of the given interface name.
 * /*from ww  w  .j av a 2s.c  o  m*/
 * @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 e)
    // {
    // e.printStackTrace();
    // return null;
    // }
}

From source file:license.regist.ReadProjectInfo.java

private static boolean checkMac(Map<Integer, String> infoMap) throws SocketException {
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    Base64 base64 = new Base64();
    int i = 12;//from  ww w.j av  a2 s. com
    for (NetworkInterface ni : Collections.list(interfaces)) {
        if (ni.getName().substring(0, 1).equalsIgnoreCase("e")) {
            if (!((String) infoMap.get(Integer.valueOf(i))).equalsIgnoreCase(ni.getName()))
                return false;
            i++;
            byte[] mac = ni.getHardwareAddress();

            if (!((String) infoMap.get(Integer.valueOf(i))).equalsIgnoreCase(base64.encodeAsString(mac))) {
                return false;
            }
            i++;
        }
    }
    return true;
}

From source file:org.esupportail.nfctagdroid.NfcTacDroidActivity.java

public static String getMacAddr() {
    try {// w  w w.  ja va 2s . co  m
        List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface nif : all) {
            if (!nif.getName().equalsIgnoreCase("wlan0"))
                continue;

            byte[] macBytes = nif.getHardwareAddress();
            if (macBytes == null) {
                return "";
            }

            StringBuilder res1 = new StringBuilder();
            for (byte b : macBytes) {
                res1.append(Integer.toHexString(b & 0xFF) + ":");
            }

            if (res1.length() > 0) {
                res1.deleteCharAt(res1.length() - 1);
            }
            return res1.toString();
        }
    } catch (Exception e) {
        throw new NfcTagDroidException("can't get mac address", e);
    }
    return "";
}

From source file:com.cyanogenmod.account.util.CMAccountUtils.java

public static String getUniqueDeviceId(Context context) {
    SharedPreferences prefs = context.getSharedPreferences(CMAccount.SETTINGS_PREFERENCES,
            Context.MODE_PRIVATE);
    String udid = prefs.getString(KEY_UDID, null);
    if (udid != null)
        return udid;
    String wifiInterface = SystemProperties.get("wifi.interface");
    if (wifiInterface != null) {
        try {/*from  ww  w . java 2 s  .co  m*/
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface networkInterface : interfaces) {
                if (wifiInterface.equals(networkInterface.getDisplayName())) {
                    byte[] mac = networkInterface.getHardwareAddress();
                    if (mac != null) {
                        StringBuilder buf = new StringBuilder();
                        for (int i = 0; i < mac.length; i++)
                            buf.append(String.format("%02X:", mac[i]));
                        if (buf.length() > 0)
                            buf.deleteCharAt(buf.length() - 1);
                        if (CMAccount.DEBUG)
                            Log.d(TAG, "using wifi mac for id : " + buf.toString());
                        return digest(prefs, context.getPackageName() + buf.toString());
                    }
                }

            }
        } catch (SocketException e) {
            Log.e(TAG, "Unable to get wifi mac address", e);
        }
    }
    //If we fail, just use android id.
    return digest(prefs, context.getPackageName()
            + Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID));
}

From source file:in.bbat.license.LicenseManager.java

public static String getMacId() {
    try {//  www .j  av a 2 s.  co m
        InetAddress localInetAddress = InetAddress.getLocalHost();
        NetworkInterface localNetworkInterface = NetworkInterface.getByInetAddress(localInetAddress);
        byte[] arrayOfByte = localNetworkInterface.getHardwareAddress();
        StringBuilder localStringBuilder = new StringBuilder();
        for (int i = 0; i < arrayOfByte.length; i++)
            localStringBuilder.append(String.format("%02X%s",
                    new Object[] { Byte.valueOf(arrayOfByte[i]), i < arrayOfByte.length - 1 ? "-" : "" }));
        return localStringBuilder.toString();
    } catch (Exception localException) {
    }
    return "";
}

From source file:Main.java

public static void printParameter(NetworkInterface ni) throws SocketException {
    System.out.println(" Name = " + ni.getName());
    System.out.println(" Display Name = " + ni.getDisplayName());
    System.out.println(" Is up = " + ni.isUp());
    System.out.println(" Support multicast = " + ni.supportsMulticast());
    System.out.println(" Is loopback = " + ni.isLoopback());
    System.out.println(" Is virtual = " + ni.isVirtual());
    System.out.println(" Is point to point = " + ni.isPointToPoint());
    System.out.println(" Hardware address = " + ni.getHardwareAddress());
    System.out.println(" MTU = " + ni.getMTU());

    System.out.println("\nList of Interface Addresses:");
    List<InterfaceAddress> list = ni.getInterfaceAddresses();
    Iterator<InterfaceAddress> it = list.iterator();

    while (it.hasNext()) {
        InterfaceAddress ia = it.next();
        System.out.println(" Address = " + ia.getAddress());
        System.out.println(" Broadcast = " + ia.getBroadcast());
        System.out.println(" Network prefix length = " + ia.getNetworkPrefixLength());
        System.out.println("");
    }/*from w w w.  jav  a  2  s.co  m*/
}

From source file:com.phonemetra.account.util.AccountUtils.java

public static String getUniqueDeviceId(Context context) {
    SharedPreferences prefs = context.getSharedPreferences(Account.SETTINGS_PREFERENCES, Context.MODE_PRIVATE);
    String udid = prefs.getString(KEY_UDID, null);
    if (udid != null)
        return udid;
    String wifiInterface = SystemProperties.get("wifi.interface");
    if (wifiInterface != null) {
        try {//from w w w. ja va  2  s .c  o m
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface networkInterface : interfaces) {
                if (wifiInterface.equals(networkInterface.getDisplayName())) {
                    byte[] mac = networkInterface.getHardwareAddress();
                    if (mac != null) {
                        StringBuilder buf = new StringBuilder();
                        for (int i = 0; i < mac.length; i++)
                            buf.append(String.format("%02X:", mac[i]));
                        if (buf.length() > 0)
                            buf.deleteCharAt(buf.length() - 1);
                        if (Account.DEBUG)
                            Log.d(TAG, "using wifi mac for id : " + buf.toString());
                        return digest(prefs, context.getPackageName() + buf.toString());
                    }
                }

            }
        } catch (SocketException e) {
            Log.e(TAG, "Unable to get wifi mac address", e);
        }
    }
    //If we fail, just use android id.
    return digest(prefs, context.getPackageName()
            + Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID));
}

From source file:org.basdroid.common.NetworkUtils.java

public static String getMacAddressFromNetworkInterface(final Context context) {

    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    int ipAddress = wifiInfo.getIpAddress();

    // Convert little-endian to big-endianif needed
    if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
        ipAddress = Integer.reverseBytes(ipAddress);
    }// w  ww .  j  a  v a 2 s. c o  m

    byte[] bytes = BigInteger.valueOf(ipAddress).toByteArray();

    String result;
    try {
        InetAddress addr = InetAddress.getByAddress(bytes);
        NetworkInterface netInterface = NetworkInterface.getByInetAddress(addr);
        Log.d(TAG, "Wifi netInterface.getName() = " + netInterface.getName());

        byte[] mac = netInterface.getHardwareAddress();
        if (mac == null || mac.length == 0)
            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 (UnknownHostException ex) {
        Log.e(TAG, "getMacAddressFromNetworkInterface() Unknown host.", ex);
        result = null;
    } catch (SocketException ex) {
        Log.e(TAG, "getMacAddressFromNetworkInterface() Socket exception.", ex);
        result = null;
    } catch (Exception ex) {
        Log.e(TAG, "getMacAddressFromNetworkInterface() Exception.", ex);
        result = null;
    }

    return result;
}

From source file:license.ExtraTestWakeLicense.java

/**
 * ?mac?/*  w  w w  .  jav  a  2s . 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++;
        }
    }
}