java 记录ip和mac地址
要记录IP和MAC地址,可以使用Java的NetworkInterface类和InetAddress类来实现。下面是一个简单的示例代码:
import java.net.*;
public class IPAndMACAddress {
public static void main(String[] args) {
try {
// 获取本地主机的网络接口
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
// 获取接口的MAC地址
byte[] mac = networkInterface.getHardwareAddress();
StringBuilder macAddress = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
macAddress.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
System.out.println("MAC地址: " + macAddress.toString());
// 获取接口的IP地址
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
if (inetAddress instanceof Inet4Address) {
System.out.println("IPv4地址: " + inetAddress.getHostAddress());
} else if (inetAddress instanceof Inet6Address) {
System.out.println("IPv6地址: " + inetAddress.getHostAddress());
}
}
} catch (SocketException | UnknownHostException e) {
e.printStackTrace();
}
}
}
该代码通过NetworkInterface.getByInetAddress()方法获取本地主机的网络接口,然后使用getHardwareAddress()方法获取MAC地址。接着使用getInetAddresses()方法获取接口的IP地址,根据返回的InetAddress对象判断是IPv4还是IPv6地址,并打印出来。
请注意,获取MAC地址需要在具有网络接口的设备上运行,并且需要适当的权限。在某些情况下,可能无法获取到MAC地址或只能获取到IPv4地址
原文地址: https://www.cveoy.top/t/topic/h0Kt 著作权归作者所有。请勿转载和采集!