Some doubts about how to get multiple IP addresses (if I have multiple network cards) in Java?

I have the following 2 problems when retrieving the ip client.

I created the following code inside the class:

private static InetAddress thisIp;

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

    }
}

My problems:

1) The previous code should get the IP address of the client, when I run it, it will print the following message:

MyIp: andrea-virtual-machine / 127.0.1.1

Why does it start with andrea-virtual-machine / ? (I am developing in a virtual machine) is this a problem?

2) Thus, I can only get one IP address, but I could have more than one network card, so I could have more than one IP address, but several IP addresses

, ? IP- ArrayList

Andrea

+4
3
  • , , , IP (hostname/ip). , : toString() InetAddress .

  • 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() .

InetAddress Inet4Address, Inet6Address, instanceof, , IP- IPv4 IPv6.

+8

, IP, , INetAddress. , , .

0

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

}
0

All Articles