[转] java获取hostIp和hostName

【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:WindowsSystem32drivershosts中的数据,如果是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地址该如何处理?

原文地址:https://www.cnblogs.com/pekkle/p/9784953.html