JAVA获取IP和Mac地址
时间: 2023-05-12 08:07:16 浏览: 131
获取IP地址可以使用Java的InetAddress类,示例代码如下:
```
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
public class IPMacAddress {
public static void main(String[] args) {
try {
InetAddress ip = InetAddress.getLocalHost();
System.out.println("IP地址:" + ip.getHostAddress());
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
byte[] mac = network.getHardwareAddress();
System.out.print("MAC地址:");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
System.out.println(sb.toString());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
}
}
}
```
获取Mac地址需要使用Java的NetworkInterface类,示例代码如下:
```
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class MacAddress {
public static void main(String[] args) {
try {
Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
while (networks.hasMoreElements()) {
NetworkInterface network = networks.nextElement();
byte[] mac = network.getHardwareAddress();
if (mac != null) {
System.out.print("MAC地址:");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
System.out.println(sb.toString());
}
}
} catch (SocketException e) {
e.printStackTrace();
}
}
}
```
阅读全文