简体   繁体   中英

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

I have the following 2 problems in retrieving the ip of a client.

I have create the following code inside a class:

private static InetAddress thisIp;

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

    }
}

My problems are:

1) The previous code should retrieve the IP address of a client, when I execute it it print the following message:

MyIp is: andrea-virtual-machine/127.0.1.1

Why it begin with andrea-virtual-machine/ ? (I am developing on a virtual machine), is it a problem?

2) In this way I can retrieve only a single IP address but I could have more than a single network card so I could have more than a single IP address but multiple IP addresses

What can I do to handle this situation? I want put all the multiple IP addresses into an ArrayList

Tnx

Andrea

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM