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.rockagen.commons.util.CommUtil.java

/**
 * Returns the hardware address (usually MAC) of the interface if it
 * has one and if it can be accessed given the current privileges.
 *
 * @return a char array containing the first address or <code>null</code> if
 * the address doesn't exist or is not accessible.
 * @throws SocketException if an I/O error occurs.
 * @since 1.6//from www.j  a va2 s. co m
 */
public static String[] getMacAddrs() throws SocketException {
    Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
    StringBuilder buf = new StringBuilder();
    while (e.hasMoreElements()) {
        NetworkInterface network = e.nextElement();
        if (network != null) {
            byte[] nmac = network.getHardwareAddress();
            if (nmac != null) {
                buf.append(hexdump(nmac));
                buf.append("#");
            }
        }
    }
    return buf.toString().split("#");
}

From source file:org.noroomattheinn.visibletesla.App.java

final String getAppID() {
    String appID = "Unidentified";
    try {//from   ww w.j  av a 2  s. co  m
        InetAddress ip = InetAddress.getLocalHost();
        NetworkInterface network = NetworkInterface.getByInetAddress(ip);
        if (network != null) {
            byte[] mac = network.getHardwareAddress();
            appID = DigestUtils.sha256Hex(mac);
        }
    } catch (UnknownHostException | SocketException e) {
        logger.warning("Unable to generate an AppID: " + e.getMessage());
    }
    return appID;
}

From source file:com.momathink.common.tools.ToolMonitor.java

/**
 * MAC? //from  w w w  .j a  va  2s. c  o  m
 * @return : "00 00 00 00 00 00"
 */
private String getMACAddr() {
    String mac = "";
    try {
        NetworkInterface netInterface = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
        byte[] macAddr = netInterface.getHardwareAddress();
        String macByte = "";
        // ????
        for (byte b : macAddr) {
            macByte = Integer.toHexString((int) (b & 0xff));
            if (macByte.length() == 1) {
                macByte = "0" + macByte;
            }
            mac = mac + " " + macByte;
        }
    } catch (Exception e) {
    }
    return mac.substring(1);
}

From source file:org.programmatori.domotica.own.plugin.system.System.java

private Value getMac() {
    Value v = null;/*from  w w  w. j  a  v  a2 s . com*/

    try {
        InetAddress thisIp = InetAddress.getLocalHost();
        boolean first = true;

        NetworkInterface networkInterface = NetworkInterface.getByInetAddress(thisIp);
        byte[] idr = networkInterface.getHardwareAddress();

        if (idr != null && idr.length > 0) {
            String val = "0";
            for (int z = 0; z < idr.length; z++) {
                if (idr[z] < 0) {
                    val = Integer.toString(256 + idr[z]);
                } else {
                    val = Integer.toString(idr[z]);
                }

                if (first) {
                    v = new Value(val);
                    first = false;
                } else {
                    v.addValue(val);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return v;
}

From source file:net.chunkyhosting.Roe.ChunkyTransactions.api.License.java

public boolean checkMac(String mac) {

    StringBuilder sb = new StringBuilder();
    try {/* w  ww .  j  a v  a2s.c  o  m*/
        NetworkInterface network = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());

        byte[] macAddr = network.getHardwareAddress();

        for (int i = 0; i < macAddr.length; i++) {

            sb.append(String.format("%02X%s", macAddr[i], (i < macAddr.length - 1) ? "-" : ""));

        }

        ChunkyTransactions.getInstance().getMessage().debug("Your Mac Address: " + sb.toString());

        this.setMac(sb.toString());

        if (sb.toString().equalsIgnoreCase(mac)) {

            return true;

        }

    } catch (SocketException e) {

        ChunkyTransactions.getInstance().getMessage().log(Level.SEVERE, "Unable to check your Mac Address");
        ChunkyTransactions.getInstance().getMessage().spitError(e);
        return false;

    } catch (UnknownHostException e) {

        ChunkyTransactions.getInstance().getMessage().log(Level.SEVERE, "Unable to check your Mac Address");
        ChunkyTransactions.getInstance().getMessage().spitError(e);
        return false;

    }

    return false;

}

From source file:ch.cyberduck.core.aquaticprime.Receipt.java

/**
 * Verifies the App Store Receipt/*from ww  w.  j a v a  2 s  .c o m*/
 *
 * @return False if receipt validation failed.
 */
@Override
public boolean verify() {
    try {
        Security.addProvider(new BouncyCastleProvider());
        PKCS7SignedData signature = new PKCS7SignedData(
                IOUtils.toByteArray(new FileInputStream(this.getFile().getAbsolute())));

        signature.verify();
        // For additional security, you may verify the fingerprint of the root CA and the OIDs of the
        // intermediate CA and signing certificate. The OID in the Certificate Policies Extension of the
        // intermediate CA is (1 2 840 113635 100 5 6 1), and the Marker OID of the signing certificate
        // is (1 2 840 113635 100 6 11 1).

        // Extract the receipt attributes
        CMSSignedData s = new CMSSignedData(new FileInputStream(this.getFile().getAbsolute()));
        CMSProcessable signedContent = s.getSignedContent();
        byte[] originalContent = (byte[]) signedContent.getContent();
        ASN1Object asn = ASN1Object.fromByteArray(originalContent);

        byte[] opaque = null;
        String bundleIdentifier = null;
        String bundleVersion = null;
        byte[] hash = null;

        if (asn instanceof DERSet) {
            // 2 Bundle identifier      Interpret as an ASN.1 UTF8STRING.
            // 3 Application version    Interpret as an ASN.1 UTF8STRING.
            // 4 Opaque value           Interpret as a series of bytes.
            // 5 SHA-1 hash             Interpret as a 20-byte SHA-1 digest value.
            DERSet set = (DERSet) asn;
            Enumeration enumeration = set.getObjects();
            while (enumeration.hasMoreElements()) {
                Object next = enumeration.nextElement();
                if (next instanceof DERSequence) {
                    DERSequence sequence = (DERSequence) next;
                    DEREncodable type = sequence.getObjectAt(0);
                    if (type instanceof DERInteger) {
                        if (((DERInteger) type).getValue().intValue() == 2) {
                            DEREncodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                bundleIdentifier = new String(((DEROctetString) value).getOctets(), "utf-8");
                            }
                        } else if (((DERInteger) type).getValue().intValue() == 3) {
                            DEREncodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                bundleVersion = new String(((DEROctetString) value).getOctets(), "utf-8");
                            }
                        } else if (((DERInteger) type).getValue().intValue() == 4) {
                            DEREncodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                opaque = ((DEROctetString) value).getOctets();
                            }
                        } else if (((DERInteger) type).getValue().intValue() == 5) {
                            DEREncodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                hash = ((DEROctetString) value).getOctets();
                            }
                        }
                    }
                }
            }
        } else {
            log.error(String.format("Expected set of attributes for %s", asn));
            return false;
        }
        if (!StringUtils.equals("ch.sudo.cyberduck", StringUtils.trim(bundleIdentifier))) {
            log.error("Bundle identifier in ASN set does not match");
            return false;
        }
        if (!StringUtils.equals(Preferences.instance().getDefault("CFBundleShortVersionString"),
                StringUtils.trim(bundleVersion))) {
            log.warn("Bundle version in ASN set does not match");
        }

        NetworkInterface en0 = NetworkInterface.getByName("en0");
        if (null == en0) {
            // Interface is not found when link is down #fail
            log.warn("No network interface en0");
        } else {
            byte[] mac = en0.getHardwareAddress();
            if (null == mac) {
                log.error("Cannot determine MAC address");
                // Continue without validation
                return true;
            }
            final String hex = Hex.encodeHexString(mac);
            if (log.isDebugEnabled()) {
                log.debug("Interface en0:" + hex);
            }
            // Compute the hash of the GUID
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(mac);
            digest.update(opaque);
            digest.update(bundleIdentifier.getBytes(Charset.forName("utf-8")));
            byte[] result = digest.digest();
            if (Arrays.equals(result, hash)) {
                if (log.isInfoEnabled()) {
                    log.info(String.format("Valid receipt for GUID %s", hex));
                }
                this.name = hex;
            } else {
                log.error(String.format("Failed verification. Hash with GUID %s does not match hash in receipt",
                        hex));
                return false;
            }
        }
    } catch (Exception e) {
        log.error("Unknown receipt validation error", e);
        // Shutdown if receipt is not valid
        return false;
    }
    // Always return true to dismiss donation prompt.
    return true;
}

From source file:ch.cyberduck.core.aquaticprime.ReceiptVerifier.java

@Override
public boolean verify(final LicenseVerifierCallback callback) {
    try {//from w ww  .  ja  v  a 2  s . c  o  m
        // For additional security, you may verify the fingerprint of the root CA and the OIDs of the
        // intermediate CA and signing certificate. The OID in the Certificate Policies Extension of the
        // intermediate CA is (1 2 840 113635 100 5 6 1), and the Marker OID of the signing certificate
        // is (1 2 840 113635 100 6 11 1).
        final CMSSignedData s = new CMSSignedData(new FileInputStream(file.getAbsolute()));
        Store certs = s.getCertificates();
        SignerInformationStore signers = s.getSignerInfos();
        for (SignerInformation signer : signers.getSigners()) {
            final Collection<X509CertificateHolder> matches = certs.getMatches(signer.getSID());
            for (X509CertificateHolder holder : matches) {
                if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder()
                        .setProvider(new BouncyCastleProvider()).build(holder))) {
                    return false;
                }
            }
        }
        // Extract the receipt attributes
        final CMSProcessable signedContent = s.getSignedContent();
        byte[] originalContent = (byte[]) signedContent.getContent();
        final ASN1Primitive asn = ASN1Primitive.fromByteArray(originalContent);

        byte[] opaque = null;
        String bundleIdentifier = null;
        String bundleVersion = null;
        byte[] hash = null;

        if (asn instanceof ASN1Set) {
            // 2 Bundle identifier      Interpret as an ASN.1 UTF8STRING.
            // 3 Application version    Interpret as an ASN.1 UTF8STRING.
            // 4 Opaque value           Interpret as a series of bytes.
            // 5 SHA-1 hash             Interpret as a 20-byte SHA-1 digest value.
            final ASN1Set set = (ASN1Set) asn;
            final Enumeration enumeration = set.getObjects();
            while (enumeration.hasMoreElements()) {
                Object next = enumeration.nextElement();
                if (next instanceof DLSequence) {
                    DLSequence sequence = (DLSequence) next;
                    ASN1Encodable type = sequence.getObjectAt(0);
                    if (type instanceof ASN1Integer) {
                        if (((ASN1Integer) type).getValue().intValue() == 2) {
                            final ASN1Encodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                bundleIdentifier = new String(((DEROctetString) value).getOctets(), "UTF-8");
                            }
                        } else if (((ASN1Integer) type).getValue().intValue() == 3) {
                            final ASN1Encodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                bundleVersion = new String(((DEROctetString) value).getOctets(), "UTF-8");
                            }
                        } else if (((ASN1Integer) type).getValue().intValue() == 4) {
                            final ASN1Encodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                opaque = ((DEROctetString) value).getOctets();
                            }
                        } else if (((ASN1Integer) type).getValue().intValue() == 5) {
                            final ASN1Encodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                hash = ((DEROctetString) value).getOctets();
                            }
                        }
                    }
                }
            }
        } else {
            log.error(String.format("Expected set of attributes for %s", asn));
            return false;
        }
        if (!StringUtils.equals(application, StringUtils.trim(bundleIdentifier))) {
            log.error(String.format("Bundle identifier %s in ASN set does not match", bundleIdentifier));
            return false;
        }
        if (!StringUtils.equals(version, StringUtils.trim(bundleVersion))) {
            log.warn(String.format("Bundle version %s in ASN set does not match", bundleVersion));
        }
        final NetworkInterface en0 = NetworkInterface.getByName("en0");
        if (null == en0) {
            // Interface is not found when link is down #fail
            log.warn("No network interface en0");
            return true;
        } else {
            final byte[] mac = en0.getHardwareAddress();
            if (null == mac) {
                log.error("Cannot determine MAC address");
                // Continue without validation
                return true;
            }
            final String hex = Hex.encodeHexString(mac);
            if (log.isDebugEnabled()) {
                log.debug(String.format("Interface en0 %s", hex));
            }
            // Compute the hash of the GUID
            final MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(mac);
            if (null == opaque) {
                log.error(String.format("Missing opaque string in ASN.1 set %s", asn));
                return false;
            }
            digest.update(opaque);
            if (null == bundleIdentifier) {
                log.error(String.format("Missing bundle identifier in ASN.1 set %s", asn));
                return false;
            }
            digest.update(bundleIdentifier.getBytes(Charset.forName("UTF-8")));
            final byte[] result = digest.digest();
            if (Arrays.equals(result, hash)) {
                if (log.isInfoEnabled()) {
                    log.info(String.format("Valid receipt for GUID %s", hex));
                }
                guid = hex;
                return true;
            } else {
                log.error(String.format("Failed verification. Hash with GUID %s does not match hash in receipt",
                        hex));
                return false;
            }
        }
    } catch (IOException | GeneralSecurityException | CMSException | SecurityException e) {
        log.error("Receipt validation error", e);
        // Shutdown if receipt is not valid
        return false;
    } catch (Exception e) {
        log.error("Unknown receipt validation error", e);
        return true;
    }
}

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

public static long getMacAddressAsLong(final InetAddress address) {
    long macAddressAsLong = 0;
    try {/*ww w.j  a v  a2s. c o m*/
        final NetworkInterface ni = NetworkInterface.getByInetAddress(address);
        final byte[] mac = ni.getHardwareAddress();

        for (int i = 0; i < mac.length; i++) {
            macAddressAsLong |= (long) (mac[i] & 0xff) << (mac.length - i - 1) * 8;
        }

    } catch (final SocketException e) {
        s_logger.error("SocketException when trying to retrieve MAC address", e);
    }

    return macAddressAsLong;
}

From source file:org.openremote.controller.service.BeehiveCommandCheckService.java

public static String getMACAddresses() throws Exception {
    StringBuilder macs = new StringBuilder();
    Enumeration<NetworkInterface> enum1 = NetworkInterface.getNetworkInterfaces();

    while (enum1.hasMoreElements()) {
        NetworkInterface networkInterface = enum1.nextElement();

        if (!networkInterface.isLoopback()) {
            boolean onlyLinkLocal = true;

            for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
                if (!interfaceAddress.getAddress().isLinkLocalAddress()) {
                    onlyLinkLocal = false;
                }/*from  ww w.j  av a 2  s  .  c  om*/
            }

            if (onlyLinkLocal) {
                continue;
            }

            byte[] mac = networkInterface.getHardwareAddress();

            if (mac != null) {
                macs.append(getMACString(networkInterface.getHardwareAddress()));
                macs.append(",");
            }
        }
    }

    if (macs.length() == 0) {
        return "no-mac-address-found";
    }

    macs.deleteCharAt(macs.length() - 1);

    return macs.toString();
}

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

public static String getMacAddress(final InetAddress address) {
    final StringBuffer sb = new StringBuffer();
    final Formatter formatter = new Formatter(sb);
    try {/*  w  w w  .  j a va  2 s.  c  o m*/
        final NetworkInterface ni = NetworkInterface.getByInetAddress(address);
        final byte[] mac = ni.getHardwareAddress();

        for (int i = 0; i < mac.length; i++) {
            formatter.format("%02X%s", mac[i], i < mac.length - 1 ? ":" : "");
        }
    } catch (final SocketException e) {
        s_logger.error("SocketException when trying to retrieve MAC address", e);
    } finally {
        formatter.close();
    }
    return sb.toString();
}