java.net.NetworkInterface#getHardwareAddress ( )源码实例Demo

下面列出了java.net.NetworkInterface#getHardwareAddress ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: jdk8u_jdk   文件: UniqueMacAddressesTest.java
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;
}
 
源代码2 项目: jdk8u-dev-jdk   文件: UniqueMacAddressesTest.java
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;
}
 
源代码3 项目: openjdk-jdk8u   文件: UniqueMacAddressesTest.java
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;
}
 
源代码4 项目: crate   文件: MacAddressProvider.java
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;
}
 
源代码5 项目: ext-opensource-netty   文件: IdWorker.java
/**
 * <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;
}
 
源代码6 项目: phoebus   文件: MQTT_PVConn.java
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);
}
 
源代码7 项目: leyou   文件: IdWorker.java
/**
 * <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;
}
 
源代码8 项目: roncoo-education   文件: IdWorker.java
/**
 * <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;
}
 
源代码9 项目: TencentKona-8   文件: UniqueMacAddressesTest.java
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;
}
 
源代码10 项目: momo-cloud-permission   文件: SnowFlake.java
/**
 * <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;
}
 
源代码11 项目: super-cloudops   文件: NetUtils.java
/**
 * 获取机器码
 */
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;
}
 
源代码12 项目: dragonwell8_jdk   文件: UniqueMacAddressesTest.java
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;
}
 
源代码13 项目: translationstudio8   文件: LinuxSeries.java
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;
		}
	}
 
源代码14 项目: dcs-sdk-java   文件: StandbyDeviceIdUtil.java
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;
}
 
源代码15 项目: letv   文件: NetworkUtils.java
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 "";
}
 
源代码16 项目: apollo   文件: MachineUtil.java
/**
 * 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;
}
 
源代码17 项目: FRC-2019-Public   文件: Constants.java
/**
 * @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 "";
}
 
源代码18 项目: heisenberg   文件: HeisenbergServer.java
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 "";
}
 
源代码19 项目: carbon-apimgt   文件: Configurator.java
/**
 * 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;
}
 
源代码20 项目: jdk8u-dev-jdk   文件: UniqueMacAddressesTest.java
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();
}