Java Code Examples for java.net.NetworkInterface#getHardwareAddress()

The following examples show how to use java.net.NetworkInterface#getHardwareAddress() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UniqueMacAddressesTest.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
private boolean testMacAddressesEqual(NetworkInterface netIf1,
        NetworkInterface netIf2) throws Exception {

    byte[] rawMacAddress1 = null;
    byte[] rawMacAddress2 = null;
    boolean macAddressesEqual = false;
    if (!netIf1.getName().equals(netIf2.getName())) {
        System.out.println("compare hardware addresses "
            +  createMacAddressString(netIf1) + " and " + createMacAddressString(netIf2));
        rawMacAddress1 = netIf1.getHardwareAddress();
        rawMacAddress2 = netIf2.getHardwareAddress();
        macAddressesEqual = Arrays.equals(rawMacAddress1, rawMacAddress2);
    } else {
        // same interface
        macAddressesEqual = false;
    }
    return macAddressesEqual;
}
 
Example 2
Source File: UniqueMacAddressesTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private boolean testMacAddressesEqual(NetworkInterface netIf1,
        NetworkInterface netIf2) throws Exception {

    byte[] rawMacAddress1 = null;
    byte[] rawMacAddress2 = null;
    boolean macAddressesEqual = false;
    if (!netIf1.getName().equals(netIf2.getName())) {
        System.out.println("compare hardware addresses "
            +  createMacAddressString(netIf1) + " and " + createMacAddressString(netIf2));
        rawMacAddress1 = netIf1.getHardwareAddress();
        rawMacAddress2 = netIf2.getHardwareAddress();
        macAddressesEqual = Arrays.equals(rawMacAddress1, rawMacAddress2);
    } else {
        // same interface
        macAddressesEqual = false;
    }
    return macAddressesEqual;
}
 
Example 3
Source File: NetUtils.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
/**
 * 获取机器码
 */
public static byte[] getMachineNum() {
	try {
		InetAddress ip = NetUtils.getLocalInetAddress();
		NetworkInterface network = NetworkInterface.getByInetAddress(ip);
		if (network != null) {
			byte[] mac = network.getHardwareAddress();
			if (null != mac) {
				return mac;
			}
		}
	} catch (Exception e) {
		logger.error("机器码获取失败:" + e.getMessage());
	}
	return null;
}
 
Example 4
Source File: SnowFlake.java    From momo-cloud-permission with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * 数据标识id部分
 * </p>
 */
protected static long getDatacenterId(long maxDatacenterId) {
    long id = 0L;
    try {
        InetAddress ip = InetAddress.getLocalHost();
        NetworkInterface network = NetworkInterface.getByInetAddress(ip);
        if (network == null) {
            id = 1L;
        } else {
            byte[] mac = network.getHardwareAddress();
            if (null != mac) {
                id = ((0x000000FF & (long) mac[mac.length - 1]) | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;
                id = id % (maxDatacenterId + 1);
            }
        }
    } catch (Exception e) {
        log.warn(" getDatacenterId: " + e.getMessage());
    }
    return id;
}
 
Example 5
Source File: UniqueMacAddressesTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private boolean testMacAddressesEqual(NetworkInterface netIf1,
        NetworkInterface netIf2) throws Exception {

    byte[] rawMacAddress1 = null;
    byte[] rawMacAddress2 = null;
    boolean macAddressesEqual = false;
    if (!netIf1.getName().equals(netIf2.getName())) {
        System.out.println("compare hardware addresses "
            +  createMacAddressString(netIf1) + " and " + createMacAddressString(netIf2));
        rawMacAddress1 = netIf1.getHardwareAddress();
        rawMacAddress2 = netIf2.getHardwareAddress();
        macAddressesEqual = Arrays.equals(rawMacAddress1, rawMacAddress2);
    } else {
        // same interface
        macAddressesEqual = false;
    }
    return macAddressesEqual;
}
 
Example 6
Source File: IdWorker.java    From roncoo-education with MIT License 6 votes vote down vote up
/**
 * <p>
 * 数据标识id部分
 * </p>
 */
protected static long getDatacenterId(long maxDatacenterId) {
	long id = 0L;
	try {
		InetAddress ip = InetAddress.getLocalHost();
		NetworkInterface network = NetworkInterface.getByInetAddress(ip);
		if (network == null) {
			id = 1L;
		} else {
			byte[] mac = network.getHardwareAddress();
			if (null != mac) {
				id = ((0x000000FF & (long) mac[mac.length - 1]) | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;
				id = id % (maxDatacenterId + 1);
			}
		}
	} catch (Exception e) {
		logger.warn(" getDatacenterId: " + e.getMessage());
	}
	return id;
}
 
Example 7
Source File: IdWorker.java    From leyou with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * 数据标识id部分
 * </p>
 */
protected static long getDatacenterId(long maxDatacenterId) {
    long id = 0L;
    try {
        InetAddress ip = InetAddress.getLocalHost();
        NetworkInterface network = NetworkInterface.getByInetAddress(ip);
        if (network == null) {
            id = 1L;
        } else {
            byte[] mac = network.getHardwareAddress();
            id = ((0x000000FF & (long) mac[mac.length - 1])
                    | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;
            id = id % (maxDatacenterId + 1);
        }
    } catch (Exception e) {
        System.out.println(" getDatacenterId: " + e.getMessage());
    }
    return id;
}
 
Example 8
Source File: MQTT_PVConn.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
private void generateClientID()
{
    try
    {
        NetworkInterface nwi = NetworkInterface.getByIndex(0);
        byte mac[] = nwi.getHardwareAddress();
        clientID = String.valueOf(mac) + String.valueOf(randInt);
    }
    catch(Exception e)
    {
        try {
            InetAddress address = InetAddress.getLocalHost();
            clientID = address.getCanonicalHostName() + String.valueOf(randInt);
        }
        catch(Exception e2)
        {
            clientID = String.valueOf(randInt);
        }
    }

    //System MAC address (or hostname) + random integer + object hash... hopefully unique?
    clientID += "-" + System.identityHashCode(this);
}
 
Example 9
Source File: IdWorker.java    From ext-opensource-netty with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * <p>
 * 数据标识id部分
 * </p>
 */
protected static long getDatacenterId(long maxDatacenterId) {
    long id = 0L;
    try {
        InetAddress ip = InetAddress.getLocalHost();
        NetworkInterface network = NetworkInterface.getByInetAddress(ip);
        if (network == null) {
            id = 1L;
        } else {
            byte[] mac = network.getHardwareAddress();
            id = ((0x000000FF & (long) mac[mac.length - 1])
                    | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;
            id = id % (maxDatacenterId + 1);
        }
    } catch (Exception e) {
        System.out.println(" getDatacenterId: " + e.getMessage());
    }
    return id;
}
 
Example 10
Source File: MacAddressProvider.java    From crate with Apache License 2.0 6 votes vote down vote up
private static byte[] getMacAddress() throws SocketException {
    Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
    if (en != null) {
        while (en.hasMoreElements()) {
            NetworkInterface nint = en.nextElement();
            if (!nint.isLoopback()) {
                // Pick the first valid non loopback address we find
                byte[] address = nint.getHardwareAddress();
                if (isValidAddress(address)) {
                    return address;
                }
            }
        }
    }
    // Could not find a mac address
    return null;
}
 
Example 11
Source File: UniqueMacAddressesTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private boolean testMacAddressesEqual(NetworkInterface netIf1,
        NetworkInterface netIf2) throws Exception {

    byte[] rawMacAddress1 = null;
    byte[] rawMacAddress2 = null;
    boolean macAddressesEqual = false;
    if (!netIf1.getName().equals(netIf2.getName())) {
        System.out.println("compare hardware addresses "
            +  createMacAddressString(netIf1) + " and " + createMacAddressString(netIf2));
        rawMacAddress1 = netIf1.getHardwareAddress();
        rawMacAddress2 = netIf2.getHardwareAddress();
        macAddressesEqual = Arrays.equals(rawMacAddress1, rawMacAddress2);
    } else {
        // same interface
        macAddressesEqual = false;
    }
    return macAddressesEqual;
}
 
Example 12
Source File: UniqueMacAddressesTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
private boolean testMacAddressesEqual(NetworkInterface netIf1,
        NetworkInterface netIf2) throws Exception {

    byte[] rawMacAddress1 = null;
    byte[] rawMacAddress2 = null;
    boolean macAddressesEqual = false;
    if (!netIf1.getName().equals(netIf2.getName())) {
        System.out.println("compare hardware addresses "
            +  createMacAddressString(netIf1) + " and " + createMacAddressString(netIf2));
        rawMacAddress1 = netIf1.getHardwareAddress();
        rawMacAddress2 = netIf2.getHardwareAddress();
        macAddressesEqual = Arrays.equals(rawMacAddress1, rawMacAddress2);
    } else {
        // same interface
        macAddressesEqual = false;
    }
    return macAddressesEqual;
}
 
Example 13
Source File: Constants.java    From FRC-2019-Public with MIT License 5 votes vote down vote up
/**
 * @return the MAC address of the robot
 */
public static String getMACAddress() {
    try {
        Enumeration<NetworkInterface> nwInterface = NetworkInterface.getNetworkInterfaces();
        StringBuilder ret = new StringBuilder();
        while (nwInterface.hasMoreElements()) {
            NetworkInterface nis = nwInterface.nextElement();
            if (nis != null) {
                byte[] mac = nis.getHardwareAddress();
                if (mac != null) {
                    for (int i = 0; i < mac.length; i++) {
                        ret.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
                    }
                    return ret.toString();
                } else {
                    System.out.println("Address doesn't exist or is not accessible");
                }
            } else {
                System.out.println("Network Interface for the specified address is not found.");
            }
        }
    } catch (SocketException | NullPointerException e) {
        e.printStackTrace();
    }

    return "";
}
 
Example 14
Source File: MachineUtil.java    From apollo with Apache License 2.0 5 votes vote down vote up
/**
 * Get the machine identifier from mac address
 *
 * @see <a href=https://github.com/mongodb/mongo-java-driver/blob/master/bson/src/main/org/bson/types/ObjectId.java>ObjectId.java</a>
 */
private static int createMachineIdentifier() {
  // build a 2-byte machine piece based on NICs info
  int machinePiece;
  try {
    StringBuilder sb = new StringBuilder();
    Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();

    if (e != null){
      while (e.hasMoreElements()) {
        NetworkInterface ni = e.nextElement();
        sb.append(ni.toString());
        byte[] mac = ni.getHardwareAddress();
        if (mac != null) {
          ByteBuffer bb = ByteBuffer.wrap(mac);
          try {
            sb.append(bb.getChar());
            sb.append(bb.getChar());
            sb.append(bb.getChar());
          } catch (BufferUnderflowException shortHardwareAddressException) { //NOPMD
            // mac with less than 6 bytes. continue
          }
        }
      }
    }

    machinePiece = sb.toString().hashCode();
  } catch (Throwable ex) {
    // exception sometimes happens with IBM JVM, use random
    machinePiece = (new SecureRandom().nextInt());
    logger.warn(
        "Failed to get machine identifier from network interface, using random number instead",
        ex);
  }
  return machinePiece;
}
 
Example 15
Source File: HeisenbergServer.java    From heisenberg with Apache License 2.0 5 votes vote down vote up
private String macAddr() {
    try {
        Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
        byte[] mac = null;
        while (allNetInterfaces.hasMoreElements()) {
            NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
            if (netInterface.isLoopback() || netInterface.isVirtual() || netInterface.isPointToPoint()
                    || !netInterface.isUp()) {
                continue;
            } else {
                mac = netInterface.getHardwareAddress();
                if (mac != null) {
                    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 (sb.length() > 0) {
			if (macAddr == null) {
				return StringUtil.EMPTY;
			}
                        LOGGER.info("本机mac地址为:" + macAddr);
                        return sb.toString();
                    }
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error("MAC地址获取失败", e);
    }
    return "";
}
 
Example 16
Source File: Configurator.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve host name, mac address of the device
 *
 * @return details Map<String, String>
 */
protected static Map<String, String> getDeviceDetails() {
    InetAddress ip;
    String hostName = "";
    String macAddress = ConfigConstants.DEFAULT_MAC_ADDRESS;
    Map<String, String> details = new HashMap();
    try {
        ip = InetAddress.getLocalHost();
        hostName = ip.getHostName();
        Enumeration<NetworkInterface> networkInterfaceEnumeration = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaceEnumeration.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaceEnumeration.nextElement();
            Enumeration<InetAddress> enumeration = networkInterface.getInetAddresses();
            for (; enumeration.hasMoreElements(); ) {
                InetAddress address = enumeration.nextElement();
                if (!address.isLoopbackAddress() && !address.isLinkLocalAddress() && address.isSiteLocalAddress()) {
                    byte[] mac = networkInterface.getHardwareAddress();
                    if (mac != null) {
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < mac.length; i++) {
                            //Construct mac address
                            sb.append(String.format("%02X%s", mac[i],
                                    (i < mac.length - 1) ? ConfigConstants.DELIMITER : ""));
                        }
                        macAddress = sb.toString();
                        break;
                    }
                }
            }
        }
    } catch (UnknownHostException | SocketException e) {
        log.error("Error while retrieving mac address", e);
        Runtime.getRuntime().exit(1);
    }
    details.put(ConfigConstants.HOST_NAME, hostName);
    details.put(ConfigConstants.MAC_ADDRESS, macAddress);
    return details;
}
 
Example 17
Source File: NetworkUtils.java    From letv with Apache License 2.0 5 votes vote down vote up
public static String getWlanMac(String delimiter) {
    try {
        Enumeration<?> e = NetworkInterface.getNetworkInterfaces();
        while (e.hasMoreElements()) {
            NetworkInterface item = (NetworkInterface) e.nextElement();
            byte[] mac = item.getHardwareAddress();
            if (mac != null && mac.length > 0 && WALN_MAC.equalsIgnoreCase(item.getName())) {
                return bytesToHexWithDelimiter(mac, delimiter);
            }
        }
    } catch (Throwable e2) {
        LogTool.e(TAG, "", e2);
    }
    return "";
}
 
Example 18
Source File: StandbyDeviceIdUtil.java    From dcs-sdk-java with Apache License 2.0 5 votes vote down vote up
private static String getMacId() {
    try {
        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(String.format("%02X:", b));
            }

            if (res1.length() > 0) {
                res1.deleteCharAt(res1.length() - 1);
            }
            return res1.toString();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return DEF_MAC;
}
 
Example 19
Source File: LinuxSeries.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
public String getSeries() {
//		try {
////			NativeInterfaces.setLibDir(new File("lib"));
//			NativeInterfaces.setLibDir(new File(FileLocator.toFileURL(Platform.getBundle("net.heartsome.cat.ts.help").getEntry("")).getPath() 
//					+ File.separator + System.getProperty("sun.arch.data.model")));
//			EthernetAddress[] macs = NativeInterfaces.getAllInterfaces();
//			String series = "";
//			for (EthernetAddress a : macs) {
//				series += a.toString() + "+";
//			}
//			return "".equals(series) ? null : StringUtils.removeColon(series.substring(0, series.length() - 1));
//		} catch (IOException e) {
//			e.printStackTrace();
//			return null;
//		}	
		
		try {
			String series = "";
			Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
					.getNetworkInterfaces();
			while (networkInterfaces.hasMoreElements()) {
				NetworkInterface network = networkInterfaces.nextElement();
				if (!network.getName().startsWith("vmnet") && !network.getName().startsWith("vboxnet")) {
					byte[] mac = network.getHardwareAddress();
					if (mac != null && mac.length == 6 && !network.isLoopback() && !network.isVirtual()) {
						StringBuilder sb = new StringBuilder();
						for (int i = 0; i < mac.length; i++) {
							sb.append(String.format("%02x", mac[i]));
						}
						sb.append("+");
						series += sb.toString();
					}
				}
			}
			return "".equals(series) ? null : series.substring(0, series.length() - 1);
		} catch (SocketException e) {
			e.printStackTrace();
			return null;
		}
	}
 
Example 20
Source File: UniqueMacAddressesTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
private String createMacAddressString (NetworkInterface netIf) throws Exception {
    byte[] macAddr = netIf.getHardwareAddress();
    StringBuilder sb =  new StringBuilder();
    if (macAddr != null) {
        for (int i = 0; i < macAddr.length; i++) {
            sb.append(String.format("%02X%s", macAddr[i],
                    (i < macAddr.length - 1) ? "-" : ""));
        }
    }
    return sb.toString();
}