下面列出了java.net.NetworkInterface#getHardwareAddress ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
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;
}
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;
}
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;
}
/**
* <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;
}
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);
}
/**
* <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;
}
/**
* <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;
}
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;
}
/**
* <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;
}
/**
* 获取机器码
*/
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;
}
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;
}
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;
}
}
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;
}
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 "";
}
/**
* 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;
}
/**
* @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 "";
}
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 "";
}
/**
* 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;
}
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();
}