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:org.nebulaframework.grid.ID.java

/**
 * Attempts to read the MAC Address of the local Network
 * Interface./*from w ww  .j a  va2 s  .  c  om*/
 * 
 * @return MAC Address as a HEX-String
 * 
 * @throws IOException if occurred during process
 */
private static String getMACAddress() throws IOException {
    StringBuilder mac = new StringBuilder();

    // Obtain NetworkInterface Reference
    NetworkInterface networkInterface = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());

    // Read MAC Address as Bytes
    byte[] macBytes = networkInterface.getHardwareAddress();

    // Check if MAC info is not available
    if (macBytes == null)
        return null;

    // Convert MAC Address to String
    for (int i = 0; i < macBytes.length; i++) {
        mac.append(String.format("%02X%s", macBytes[i], (i < macBytes.length - 1) ? "-" : ""));
    }

    return mac.deleteCharAt(mac.length() - 1).toString();
}

From source file:Main.java

public static String getWifiMac(Context context) {
    String macAddr;/* www .  ja  v  a  2 s . co m*/
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    macAddr = wifiInfo.getMacAddress();
    if (TextUtils.isEmpty(macAddr)) {
        NetworkInterface networkInterface = null;
        try {
            networkInterface = NetworkInterface.getByInetAddress(InetAddress.getByName(getIPAddr()));
            byte[] hardwareAddress = networkInterface.getHardwareAddress();
            macAddr = byte2hex(hardwareAddress);
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
    return macAddr;
}

From source file:com.asquareb.kaaval.MachineKey.java

/**
 * Method to decrypt a string. Accepts the string to be decrypted and the
 * name of the file which stores the key values
 *//*from   w ww .ja v a 2  s  .  c  om*/
public static String decrypt(String property, String app) throws IOException, KaavalException {
    SecretKey key = null;
    ObjectInputStream is = null;
    MachineKey mKey = null;
    int eti = 0;
    Cipher pbeCipher = null;
    InetAddress ip = InetAddress.getLocalHost();
    NetworkInterface macAddress = NetworkInterface.getByInetAddress(ip);
    byte[] macId = macAddress.getHardwareAddress();
    try {
        is = new ObjectInputStream(new BufferedInputStream(new FileInputStream(app)));
        mKey = (MachineKey) is.readObject();
        key = mKey.yek;
        salt = mKey.tlas;
        eti = mKey.eti;
        String ipa = ip.getHostAddress();
        if (!ipa.equals(mKey.api) || !new String(macId).equals(mKey.macad))
            throw new KaavalException(5, "Key file is not for this machine");
        is.close();
        pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(salt, eti));
        return new String(pbeCipher.doFinal(base64Decode(property)));
    } catch (IOException e) {
        throw new KaavalException(3, "Error in reading key file during decryption", e);
    } catch (KaavalException e) {
        throw e;
    } catch (Exception e) {
        throw new KaavalException(4, "Error during decryption", e);
    } finally {
        if (is != null)
            is.close();
    }
}

From source file:Main.java

/**
 * Returns MAC address of the given interface name.
 *
 * @param interfaceName eth0, wlan0 or NULL=use first interface
 * @return mac address or empty string//from  w  w w. ja  va  2 s  .  com
 */
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;
    }*/
}

From source file:codeOrchestra.lcs.license.ActivationReporter.java

private static String getFingerPrint() {
    StringBuilder resultSB = new StringBuilder();
    try {/*from   w ww  .  j a  va 2 s.co  m*/
        for (final Enumeration<NetworkInterface> interfaces = NetworkInterface
                .getNetworkInterfaces(); interfaces.hasMoreElements();) {
            final NetworkInterface networkInterface = (NetworkInterface) interfaces.nextElement();
            if (networkInterface.isLoopback()) {
                continue;
            }

            byte[] mac = networkInterface.getHardwareAddress();
            if (mac == null) {
                continue;
            }

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mac.length; i++) {
                sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
            }

            if ("00-00-00-00-00-00-00-E0".equals(sb.toString())) {
                continue;
            }

            resultSB.append(sb);
            if (interfaces.hasMoreElements()) {
                resultSB.append("|");
            }
        }
    } catch (Exception e) {
        // ignore
    }

    String result = resultSB.toString();
    if (result.endsWith("|")) {
        return result.substring(0, result.length() - 1);
    }

    return result;
}

From source file:com.ddubyat.develop.jhawtcode.web.InternalResourceController.java

private static void setTraceProps(HttpServletRequest request) throws UnsupportedEncodingException {
    log.trace("Generating system properties");
    if (systemUUID.equalsIgnoreCase("")) {
        try {//w w w .  j a  v a  2 s .co  m
            //generate from hardware
            Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
            while (nis.hasMoreElements()) {
                NetworkInterface ni = nis.nextElement();
                systemUUID += Arrays.toString(ni.getHardwareAddress());
            }
        } catch (Exception e) {
            //generate a uuid randomly for failures
            systemUUID = UUID.randomUUID().toString();
        }
        //md5 the uuid
        try {
            byte[] bytesOfMessage = systemUUID.getBytes("UTF-8");
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] thedigest = md.digest(bytesOfMessage);
            systemUUID = new BigInteger(1, thedigest).toString(16);
            log.trace("UUID Generated {}", systemUUID);
        } catch (Exception e) {
            systemUUID = "1234567890";
            log.trace("UUID Defaulted {}", systemUUID);
        }
    }

    log.trace("Generating app name");
    if (appname.equalsIgnoreCase("")) {
        if (request.getSession() != null && request.getSession().getServletContext() != null
                && request.getSession().getServletContext().getServletContextName() != null) {
            appname = request.getServletContext().getServletContextName();
            log.trace("Application Name Set to {}", appname);
        } else {
            appname = "noappname";
        }
        log.trace("Appname {}", appname);
    }

    log.trace("Generating username");
    if (username.equalsIgnoreCase("")) {
        if (System.getProperty("user.name") != null && StringUtil.isNotEmpty(System.getProperty("user.name"))) {
            username = System.getProperty("user.name");
            log.trace("Username Set to {}", username);
        } else {
            username = "nouser";
        }
        log.trace("Username {}", username);
    }

    log.trace("Generating license info");
    if (license.equalsIgnoreCase("")) {
        if (System.getProperty("jhawtcode.license") != null
                && StringUtil.isNotEmpty(System.getProperty("jhawtcode.license"))) {
            license = System.getProperty("jhawtcode.license");
        } else {
            license = "demo";
        }
        license = URLEncoder.encode(license, "UTF-8");
        log.trace("License {}", license);
    }
}

From source file:eu.codebits.plasmas.util.NetworkInterfaces.java

/**
 *
 * @param interfaceName//ww  w.  j  a  v a 2 s  .co  m
 * @return
 */
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)
                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);
            return buf.toString();
        }
    } catch (SocketException ex) {
    }
    return "";
}

From source file:net.bioclipse.dbxp.business.DbxpManager.java

public static String getMacAddress() throws SocketException, UnknownHostException {
    InetAddress ip = InetAddress.getLocalHost();
    NetworkInterface network = NetworkInterface.getByInetAddress(ip);
    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) ? "" : ""));
    }/*from  ww w . j  av a 2  s .c o  m*/
    //System.out.println(sb.toString());
    return sb.toString();
}

From source file:com.ihelpoo.app.common.DeviceUtil.java

/**
 * Returns MAC address of the given interface name.
 *
 * @param interfaceName eth0, wlan0 or NULL=use first interface
 * @return mac address or empty string/*w  w  w .  jav  a2  s.  c  o  m*/
 */
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
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;
    }*/
}

From source file:com.kevinshen.beyondupnp.util.Utils.java

/**
 * Returns MAC address of the given interface name.
 *
 * @param interfaceName eth0, wlan0 or NULL=use first interface
 * @return mac address or empty string//ww w. jav a 2  s  . co  m
 */
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 "";
}