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:\Windows\System32\drivers\hosts中的數據,如果是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地址該如何處理?