Some doubts about how to retrieve multiple IP addresses (if I have more than one network card) in Java?

烂漫一生 提交于 2019-12-04 09:49:28
  1. No, it's not a problem, it's simply an output that consists of hostname and IP (hostname/ip). A detail that you might want to read up: The method toString() in the class InetAddress is implemented to return this format.

  2. The following code will list all IP addresses for each of the interfaces in your system (and also stores them in a list that you could then pass on etc...):

    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());
            }
        }
    }
    

The method boolean isLoopbackAddress() allows you to filter the potentially unwanted loopback addresses.

The returned InetAddress is either a Inet4Address or a Inet6Address, using the instanceof you can figure out if the returned IP is IPv4 or IPv6 format.

The hostname listed before the IP, incidentally, is part of INetAddress. You get both the name and the address because you didn't try to show only the address.

if your system is configured with multiple ip then do like this.

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) {

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!