InetAddress的构造函数不是公开的(public),所以需要通过它提供的静态方法来获取,有以下的方法:
static InetAddress[] getAllByName(String host)
static InetAddress getByAddress(byte[] addr)
static InetAddress getByAddress(String host,byte[] addr)
static InetAddress getByName(String host)
static InetAddress getLocalHost()
java获取本地ip信息时getLocalHost(),匹配C:WindowsSystem32drivershosts中的数据,如果是windows系统可以直接调用getLocalHost()获得。但是如果是多个网口取值的数据未知。
但是linux系统则会找到localhost.localdomain:127.0.0.1
所以想获得真正的ip4地址,需要从网口的地址进行筛选
1 public static InetAddress getInetAddress() throws SocketException{ 2 Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces(); 3 InetAddress ipHost = null; 4 while (allNetInterfaces.hasMoreElements()) { 5 NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement(); 6 Enumeration<InetAddress> addresses = netInterface.getInetAddresses(); 7 while (addresses.hasMoreElements()) { 8 ipHost = (InetAddress) addresses.nextElement(); 9 if (ipHost != null && ipHost instanceof Inet4Address) { 10 System.out.println("本机的HOSTIP = " + ipHost.getHostAddress()); 11 System.out.println("本机的HOSTNAME = " + ipHost.getHostName()); 12 return ipHost; 13 } 14 } 15 } 16 return ipHost; 17 }
问题来了:
如果主机有多个ipv4地址该如何处理?