JDK1.6 获取操作系统IP地址及对应物理mac地址

来源:互联网 发布:windows如何打钢筋符号 编辑:程序博客网 时间:2024/05/22 16:41
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;


public class OSInfo {
public static void listIPMac() throws SocketException{
//首先获取到机器的所有网络接口
Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
NetworkInterface ni = null;

//网卡的物理mac地址二进制格式
byte[] macbyte = null;

//网卡的物理mac地址
String mac = null;

//遍历所有的网络接口
while(nis.hasMoreElements()){
ni = nis.nextElement();

//当不是回环网卡,并且启动,并且不是虚拟网卡
if(!ni.isLoopback() && ni.isUp() && !ni.isVirtual()){
macbyte = ni.getHardwareAddress();
//把二进制格式化成十六进制
mac = bytesToHexString(macbyte, macbyte.length);
Enumeration<InetAddress> ias = ni.getInetAddresses();
InetAddress ia = null;
while(ias.hasMoreElements()){
ia = ias.nextElement();
//不是 127.0.0.1 回环IP
if(!ia.isLoopbackAddress()){
System.out.println(ia.getHostAddress()+" = " + mac.toUpperCase());
}
}
}
}
}

/*
 * 二进制转十六进制
 */
public static String bytesToHexString(byte[] src, int length) {
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();


}

public static void main(String[] args) {
try {
listIPMac();
} catch (SocketException e) {
e.printStackTrace();
}
}

}


运行结果:

2001:0:4137:9e76:3804:5134:2249:d190 = 00000000000000e0
fe80:0:0:0:3804:5134:2249:d190%11 = 00000000000000e0
fe80:0:0:0:b8c8:25a3:8cb6:a0b7%13 = 0015af5*****
192.168.1.101 = 0015af5*****

原创粉丝点击