有些人怀疑如何在Java中检索多个IP地址(如果我有多个网卡)



我在检索客户端的ip时遇到以下两个问题。

我在一个类中创建了以下代码:

private static InetAddress thisIp;
static{
    try {
        thisIp  = InetAddress.getLocalHost();
        System.out.println("MyIp is: " + thisIp);
    } catch(UnknownHostException ex) {
    }
}

我的问题是:

1) 前面的代码应该检索客户端的IP地址,当我执行它时,它会打印以下消息:

MyIp是:andrea虚拟机/127.0.1.1

为什么它以andrea虚拟机//strong>开头?(我在虚拟机上开发),这是个问题吗?

2) 通过这种方式,我只能检索单个IP地址,但我可以拥有多个网卡,因此我可以拥有不止一个IP地址,但是多个IP地址

我能做些什么来处理这种情况?我想将所有多个IP地址放入ArrayList

Tnx

Andrea

  1. 不,这不是问题,它只是一个由主机名和IP(hostname/ip)组成的输出。您可能想了解的一个细节是:类InetAddress中的方法toString()被实现为返回此格式。

  2. 以下代码将列出系统中每个接口的所有IP地址(并将它们存储在一个列表中,然后您可以传递这些地址等):

    public static void main(String[] args) throws InterruptedException, IOException
    {
        List<String> allIps = new ArrayList<String>();
        Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
        while (e.hasMoreElements())
        {
            NetworkInterface n = e.nextElement();
            System.out.println(n.getName());
            Enumeration<InetAddress> ee = n.getInetAddresses();
            while (ee.hasMoreElements())
            {
                InetAddress i = ee.nextElement();
                System.out.println(i.getHostAddress());
                allIps.add(i.getHostAddress());
            }
        }
    }
    

方法boolean isLoopbackAddress()允许您过滤可能不需要的环回地址。

返回的InetAddressInet4AddressInet6Address,使用instanceof可以确定返回的IP是IPv4格式还是IPv6格式。

如果您的系统配置有多个ip,那么就这样做。

try {
  InetAddress inet = InetAddress.getLocalHost();
  InetAddress[] ips = InetAddress.getAllByName(inet.getCanonicalHostName());
  if (ips  != null ) {
    for (int i = 0; i < ips.length; i++) {
      System.out.println(ips[i]);
    }
  }
} catch (UnknownHostException e) {
}

顺便提一下,IP前面列出的主机名是INetAddress的一部分。你得到了名字和地址,因为你没有试图只显示地址。

最新更新