1、获取当前网络ip和mac地址
private static String getIpAndMacAddress() {
String ip = "";
boolean isBreak = false;
String name = "";
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
name = intf.getName();
for (Enumeration<InetAddress> enumIpAddr = intf
.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()
&& inetAddress instanceof Inet4Address) {
ip = inetAddress.getHostAddress().toString();
isBreak = true;
break;
}
}
if (isBreak) {
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
String mac = "";
if (!TextUtils.isEmpty(name)) {
try {
byte[] address = NetworkInterface.getByName(name)
.getHardwareAddress();
if (address != null) {
mac = byte2hex(address, address.length);
}
} catch (SocketException e) {
e.printStackTrace();
}
}
if (!TextUtils.isEmpty(mac) && !TextUtils.isEmpty(ip)) {
return ip + "_" + mac;
}
return "";
}
private static String byte2hex(byte[] b, int length) {
StringBuffer hs = new StringBuffer(length);
String stmp = "";
int len = length;
for (int n = 0; n < len; n++) {
stmp = Integer.toHexString(b[n] & 0xFF);
if (stmp.length() == 1)
hs = hs.append("0").append(stmp);
else {
hs = hs.append(stmp);
}
if (n != len - 1) {
hs.append(":");
}
}
return String.valueOf(hs);
}