Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 485
AndreaNobili Avatar asked Feb 15 '23 12:02

AndreaNobili


1 Answers

  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.

like image 135
reto Avatar answered Feb 17 '23 01:02

reto