【From】 https://www.cnblogs.com/huluyisheng/p/6867370.html
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地址,需要從網口的地址進行篩選:
public static InetAddress getInetAddress() throws SocketException{ Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ipHost = null; while (allNetInterfaces.hasMoreElements()) { NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement(); Enumeration<InetAddress> addresses = netInterface.getInetAddresses(); while (addresses.hasMoreElements()) { ipHost = (InetAddress) addresses.nextElement(); if (ipHost != null && ipHost instanceof Inet4Address) { System.out.println("本機的HOSTIP = " + ipHost.getHostAddress()); System.out.println("本機的HOSTNAME = " + ipHost.getHostName()); return ipHost; } } } return ipHost; }
問題來了:
如果主機有多個ipv4地址該如何處理?