方式一:通过java.net.InetAddress类获取
public void test1() { try { InetAddress addr = InetAddress.getLocalHost(); System.out.println("IP地址:" + addr.getHostAddress() + ",主机名:" + addr.getHostName()); } catch (UnknownHostException e) { e.printStackTrace(); } }
输出:
IP地址:192.168.153.1,主机名:DESKTOP-338UP3E
这种方式获取到的主机名没啥问题,这种方式获取的主机名没啥问题,但获取到的IP地址却有待考量,如果一台机器有多个网卡,他获取的IP是谁的呢?事实上,上面输出的IP是我虚拟机IP地址,既不是我有线网卡的地址,也不是我无线网卡的地址。
方式二:利用java.net.NetworkInterface获取
public void test2() { try { Enumeration<NetworkInterface> faces = NetworkInterface.getNetworkInterfaces(); while (faces.hasMoreElements()) { // 遍历网络接口 NetworkInterface face = faces.nextElement(); if (face.isLoopback() || face.isVirtual() || !face.isUp()) { continue; } System.out.print("网络接口名:" + face.getDisplayName() + ",地址:"); Enumeration<InetAddress> address = face.getInetAddresses(); while (address.hasMoreElements()) { // 遍历网络地址 InetAddress addr = address.nextElement(); if (!addr.isLoopbackAddress() && addr.isSiteLocalAddress() && !addr.isAnyLocalAddress()) { System.out.print(addr.getHostAddress() + " "); } } System.out.println(""); } } catch (SocketException e) { e.printStackTrace(); } }
输出:
网络接口名:VMware Virtual Ethernet Adapter for VMnet8,地址:192.168.153.1
网络接口名:TAP-Windows Adapter V9,地址:10.8.0.30
网络接口名:VMware Virtual Ethernet Adapter for VMnet1,地址:192.168.46.1
网络接口名:Intel(R) Dual Band Wireless-AC 8265,地址:172.16.78.27
疑问?:第一、三行为VM虚拟机网络地址,不知为何还在。