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

Java 获取 IP 和 MAC 地址:完整代码示例与说明

原文地址: http://www.cveoy.top/t/topic/pJNW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录