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.apache.nifi.processors.rt.DeviceRegistryReportingTask.java

private NiFiDevice populateNetworkingInfo(NiFiDevice device) {

    InetAddress ip;//from   w w  w . j a v a 2  s  .c o  m
    try {

        ip = InetAddress.getLocalHost();

        NetworkInterface network = NetworkInterface.getByInetAddress(ip);

        //Check this isn't null
        if (network == null) {
            //Hail mary to try and get eth0
            getLogger().warn(
                    "Hardcoded getting network interface by ETH0 which could be the incorrect interface but others were null");
            network = NetworkInterface.getByName("eth0");
        }

        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) ? ":" : ""));
        }

        //Set the values to the device object.
        device.setDeviceId(sb.toString());
        device.setIp(ip.getHostAddress());

        String hostname = InetAddress.getLocalHost().getHostName();
        logger.error("First attempt at getting hostname: " + hostname);
        if (!StringUtils.isEmpty(hostname)) {
            device.setHostname(hostname);
        } else {
            //Try the linux approach ... could fail if hostname(1) system command is not available.
            try {
                Process process = Runtime.getRuntime().exec("hostname");
                InputStream is = process.getInputStream();

                StringWriter writer = new StringWriter();
                IOUtils.copy(is, writer, "UTF-8");
                hostname = writer.toString();
                if (StringUtils.isEmpty(hostname)) {
                    device.setHostname("UNKNOWN");
                } else {
                    device.setHostname(hostname);
                }

            } catch (Exception ex) {
                ex.printStackTrace();
                logger.error("Error attempting to resolve hostname", ex);
            }
        }

    } catch (UnknownHostException e) {
        e.printStackTrace();
        logger.error("Unknown host exception getting hostname", e);
    } catch (SocketException e) {
        e.printStackTrace();
        logger.error("socket exception getting hostname", e);
    }

    return device;
}

From source file:com.at.lic.LicenseControl.java

private String getMAC() throws Exception {
    String mac = "1:2:3:4:5:6:7:8"; // default mac address

    InetAddress addr = InetAddress.getLocalHost();
    NetworkInterface ni = NetworkInterface.getByInetAddress(addr);

    if (ni.isLoopback() || ni.isVirtual()) {
        ni = null;//  w ww  . j av a  2s.  c om
        Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
        while (nis.hasMoreElements()) {
            NetworkInterface aNI = (NetworkInterface) nis.nextElement();
            if (!aNI.isLoopback() && !aNI.isVirtual()) {
                ni = aNI;
                break;
            }
        }
    }

    if (ni != null) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(baos);
        byte[] HAs = ni.getHardwareAddress();
        for (int i = 0; i < HAs.length; i++) {
            ps.format("%02X:", HAs[i]);
        }
        mac = baos.toString();
        if (mac.length() > 0) {
            mac = mac.replaceFirst(":$", "");
        }

        ps.close();
        baos.close();

    }

    return mac;
}

From source file:org.structr.util.StructrLicenseManager.java

private String createHash() {

    try {/*from ww  w  .j  a v  a 2s.  c o  m*/

        final MessageDigest digest = MessageDigest.getInstance("MD5");

        // use network interface hardware addresses for host identification
        for (final NetworkInterface iface : getNetworkInterfaces()) {

            try {
                final byte[] hardwareAddress = iface.getHardwareAddress();
                if (hardwareAddress != null) {

                    digest.update(hardwareAddress);
                }

            } catch (SocketException ex) {
            }
        }

        return Hex.encodeHexString(digest.digest());

    } catch (NoSuchAlgorithmException ex) {
        logger.warn("Unable to create hardware hash.", ex);
    }

    return null;
}

From source file:org.wso2.carbon.analytics.dataservice.indexing.AnalyticsDataIndexer.java

private String getLocalUniqueId() {
    String id = null;//from  w ww  .ja va2 s  . c o m
    Enumeration<NetworkInterface> interfaces;
    NetworkInterface nif;
    try {
        interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            nif = interfaces.nextElement();
            if (!nif.isLoopback()) {
                byte[] addr = nif.getHardwareAddress();
                if (addr != null) {
                    id = this.byteArrayToHexString(addr);
                }
                /* only try first valid one, if we can't get it from here, 
                 * we wont be able to get it */
                break;
            }
        }
    } catch (SocketException ignore) {
        /* ignore */
    }
    if (id == null) {
        log.warn("CANNOT LOOK UP UNIQUE LOCAL ID USING A VALID NETWORK INTERFACE HARDWARE ADDRESS, "
                + "REVERTING TO LOCAL SINGLE NODE MODE, THIS WILL NOT WORK PROPERLY IN A CLUSTER, "
                + "AND MAY CAUSE INDEX CORRUPTION");
        /* a last effort to get a unique number, Java system properties should also take in account of the 
         * server's port offset */
        id = LOCAL_NODE_ID + ":" + (System.getenv().hashCode() + System.getProperties().hashCode());
    }
    return id;
}

From source file:com.mozilla.SUTAgentAndroid.SUTAgentAndroid.java

/** Called when the activity is first created. */
@Override//from  w w w .j  ava 2s  . c  o  m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    fixScreenOrientation();

    DoCommand dc = new DoCommand(getApplication());

    Log.i("SUTAgentAndroid", dc.prgVersion);
    dc.FixDataLocalPermissions();

    // Get configuration settings from "ini" file
    File dir = getFilesDir();
    File iniFile = new File(dir, "SUTAgent.ini");
    String sIniFile = iniFile.getAbsolutePath();

    String lc = dc.GetIniData("General", "LogCommands", sIniFile);
    if (lc != "" && Integer.parseInt(lc) == 1) {
        SUTAgentAndroid.LogCommands = true;
    }
    SUTAgentAndroid.RegSvrIPAddr = dc.GetIniData("Registration Server", "IPAddr", sIniFile);
    SUTAgentAndroid.RegSvrIPPort = dc.GetIniData("Registration Server", "PORT", sIniFile);
    SUTAgentAndroid.HardwareID = dc.GetIniData("Registration Server", "HARDWARE", sIniFile);
    SUTAgentAndroid.Pool = dc.GetIniData("Registration Server", "POOL", sIniFile);
    SUTAgentAndroid.sTestRoot = dc.GetIniData("Device", "TestRoot", sIniFile);
    SUTAgentAndroid.Abi = android.os.Build.CPU_ABI;
    log(dc, "onCreate");

    dc.SetTestRoot(SUTAgentAndroid.sTestRoot);

    Log.i("SUTAgentAndroid", "Test Root: " + SUTAgentAndroid.sTestRoot);

    tv = (TextView) this.findViewById(R.id.Textview01);

    if (getLocalIpAddress() == null)
        setUpNetwork(sIniFile);

    String macAddress = "Unknown";
    if (android.os.Build.VERSION.SDK_INT > 8) {
        try {
            NetworkInterface iface = NetworkInterface
                    .getByInetAddress(InetAddress.getAllByName(getLocalIpAddress())[0]);
            if (iface != null) {
                byte[] mac = iface.getHardwareAddress();
                if (mac != null) {
                    StringBuilder sb = new StringBuilder();
                    Formatter f = new Formatter(sb);
                    for (int i = 0; i < mac.length; i++) {
                        f.format("%02x%s", mac[i], (i < mac.length - 1) ? ":" : "");
                    }
                    macAddress = sUniqueID = sb.toString();
                }
            }
        } catch (UnknownHostException ex) {
        } catch (SocketException ex) {
        }
    } else {
        // Fall back to getting info from wifiman on older versions of Android,
        // which don't support the NetworkInterface interface
        WifiManager wifiMan = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        if (wifiMan != null) {
            WifiInfo wifi = wifiMan.getConnectionInfo();
            if (wifi != null)
                macAddress = wifi.getMacAddress();
            if (macAddress != null)
                sUniqueID = macAddress;
        }
    }

    if (sUniqueID == null) {
        BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
        if ((ba != null) && (ba.isEnabled() != true)) {
            ba.enable();
            while (ba.getState() != BluetoothAdapter.STATE_ON) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            sUniqueID = ba.getAddress();

            ba.disable();
            while (ba.getState() != BluetoothAdapter.STATE_OFF) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } else {
            if (ba != null) {
                sUniqueID = ba.getAddress();
                sUniqueID.toLowerCase();
            }
        }
    }

    if (sUniqueID == null) {
        TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        if (mTelephonyMgr != null) {
            sUniqueID = mTelephonyMgr.getDeviceId();
            if (sUniqueID == null) {
                sUniqueID = "0011223344556677";
            }
        }
    }

    String hwid = getHWID(this);

    sLocalIPAddr = getLocalIpAddress();
    Toast.makeText(getApplication().getApplicationContext(), "SUTAgent [" + sLocalIPAddr + "] ...",
            Toast.LENGTH_LONG).show();

    String sConfig = dc.prgVersion + lineSep;
    sConfig += "Test Root: " + sTestRoot + lineSep;
    sConfig += "Unique ID: " + sUniqueID + lineSep;
    sConfig += "HWID: " + hwid + lineSep;
    sConfig += "ABI: " + Abi + lineSep;
    sConfig += "OS Info" + lineSep;
    sConfig += "\t" + dc.GetOSInfo() + lineSep;
    sConfig += "Screen Info" + lineSep;
    int[] xy = dc.GetScreenXY();
    sConfig += "\t Width: " + xy[0] + lineSep;
    sConfig += "\t Height: " + xy[1] + lineSep;
    sConfig += "Memory Info" + lineSep;
    sConfig += "\t" + dc.GetMemoryInfo() + lineSep;
    sConfig += "Network Info" + lineSep;
    sConfig += "\tMac Address: " + macAddress + lineSep;
    sConfig += "\tIP Address: " + sLocalIPAddr + lineSep;

    displayStatus(sConfig);

    sRegString = "NAME=" + sUniqueID;
    sRegString += "&IPADDR=" + sLocalIPAddr;
    sRegString += "&CMDPORT=" + 20701;
    sRegString += "&DATAPORT=" + 20700;
    sRegString += "&OS=Android-" + dc.GetOSInfo();
    sRegString += "&SCRNWIDTH=" + xy[0];
    sRegString += "&SCRNHEIGHT=" + xy[1];
    sRegString += "&BPP=8";
    sRegString += "&MEMORY=" + dc.GetMemoryConfig();
    sRegString += "&HARDWARE=" + HardwareID;
    sRegString += "&POOL=" + Pool;
    sRegString += "&ABI=" + Abi;

    String sTemp = Uri.encode(sRegString, "=&");
    sRegString = "register " + sTemp;

    pruneCommandLog(dc.GetSystemTime(), dc.GetTestRoot());

    if (!bNetworkingStarted) {
        Thread thread = new Thread(null, doStartService, "StartServiceBkgnd");
        thread.start();
        bNetworkingStarted = true;

        Thread thread2 = new Thread(null, doRegisterDevice, "RegisterDeviceBkgnd");
        thread2.start();
    }

    monitorBatteryState();

    // If we are returning from an update let'em know we're back
    Thread thread3 = new Thread(null, doUpdateCallback, "UpdateCallbackBkgnd");
    thread3.start();

    final Button goButton = (Button) findViewById(R.id.Button01);
    goButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            finish();
        }
    });
}

From source file:org.springframework.vault.authentication.MacAddressUserId.java

@Override
public String createUserId() {

    try {//w ww  .ja v  a2  s  .  c o m

        NetworkInterface networkInterface = null;
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());

        if (StringUtils.hasText(networkInterfaceHint)) {

            try {
                networkInterface = getNetworkInterface(Integer.parseInt(networkInterfaceHint), interfaces);
            } catch (NumberFormatException e) {
                networkInterface = getNetworkInterface((networkInterfaceHint), interfaces);
            }
        }

        if (networkInterface == null) {

            if (StringUtils.hasText(networkInterfaceHint)) {
                log.warn(String.format("Did not find a NetworkInterface applying hint %s",
                        networkInterfaceHint));
            }

            InetAddress localHost = InetAddress.getLocalHost();
            networkInterface = NetworkInterface.getByInetAddress(localHost);

            if (networkInterface == null) {
                throw new IllegalStateException(
                        String.format("Cannot determine NetworkInterface for %s", localHost));
            }
        }

        byte[] mac = networkInterface.getHardwareAddress();
        if (mac == null) {
            throw new IllegalStateException(
                    String.format("Network interface %s has no hardware address", networkInterface.getName()));
        }

        return Sha256.toSha256(Sha256.toHexString(mac));
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.cloud.utils.net.NetUtils.java

public static String[] getNetworkParams(final NetworkInterface nic) {
    final List<InterfaceAddress> addrs = nic.getInterfaceAddresses();
    if (addrs == null || addrs.size() == 0) {
        return null;
    }//from  www.  j av a2 s  .  c om
    InterfaceAddress addr = null;
    for (final InterfaceAddress iaddr : addrs) {
        final InetAddress inet = iaddr.getAddress();
        if (!inet.isLinkLocalAddress() && !inet.isLoopbackAddress() && !inet.isMulticastAddress()
                && inet.getAddress().length == 4) {
            addr = iaddr;
            break;
        }
    }
    if (addr == null) {
        return null;
    }
    final String[] result = new String[3];
    result[0] = addr.getAddress().getHostAddress();
    try {
        final byte[] mac = nic.getHardwareAddress();
        result[1] = byte2Mac(mac);
    } catch (final SocketException e) {
        s_logger.debug("Caught exception when trying to get the mac address ", e);
    }

    result[2] = prefix2Netmask(addr.getNetworkPrefixLength());
    return result;
}

From source file:rems.Global.java

public static String[] getMachDetails() {
    System.setProperty("java.net.preferIPv4Stack", "true");
    String[] nameIP = new String[3];
    nameIP[0] = "";
    nameIP[1] = "";
    nameIP[2] = "";
    InetAddress ip;/*w  ww .j ava2  s .com*/
    String hostname;
    try {
        ip = InetAddress.getLocalHost();
        /*Enumeration e = NetworkInterface.getNetworkInterfaces();
        while (e.hasMoreElements()) {
        NetworkInterface n = (NetworkInterface) e.nextElement();
        //
        if (n.isLoopback() || n.isVirtual() || !n.isUp()) {
                
        } else if (n.isUp()) {
            Enumeration ee = n.getInetAddresses();
            while (ee.hasMoreElements()) {
                InetAddress i = (InetAddress) ee.nextElement();
                //System.out.println(i.getHostAddress());
                //nameIP[2] = i.getHostAddress();
                ip = i;
                //break;
            }
            //break;
        }
        }*/
        nameIP[2] = ip.getHostAddress();
        hostname = ip.getHostName();
        nameIP[0] = hostname;
        //System.out.println("Current IP address : " + ip.getHostAddress());
        NetworkInterface network = NetworkInterface.getByInetAddress(ip);
        byte[] mac = network.getHardwareAddress();
        //System.out.print("Current MAC address : ");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < mac.length; i++) {
            sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
        }
        //System.out.println(sb.toString());
        nameIP[1] = sb.toString();
        return nameIP;
    } catch (SocketException e) {
        return nameIP;
    } catch (UnknownHostException ex) {
        return nameIP;
    } catch (Exception ex) {
        return nameIP;
    }
}