views:

2045

answers:

5

Hello,

How to get the ip of the computer on linux through Java ?

I searched the net for examples, I found something regarding NetworkInterface class, but I can't wrap my head around how I get the Ip address.

What happens if I have multiple network interfaces running in the same time ? Which Ip address will be returned.

I would really appreciate some code samples.

P.S: I've used until now the InetAddress class which is a bad solution for cross-platform applications. (win/Linux).

+1  A: 

What you're looking for specifically is java.net.InetAddress.getHostAddress(), here is a working example:

try {
   java.net.InetAddress i = java.net.InetAddress.getLocalHost();
   System.out.println(i);                  // name and IP address
   System.out.println(i.getHostName());    // name
   System.out.println(i.getHostAddress()); // IP address only
   }
   catch(Exception e){e.printStackTrace();}
karim79
+8  A: 

From Java Tutorial

Why is InetAddress not a good solution? I don't see anything in the docs about cross platform compatibility?

This code will enumerate all network interfaces and retrieve their information.


    import java.io.*;
    import java.net.*;
    import java.util.*;
    import static java.lang.System.out;

    public class ListNets 
    {
        public static void main(String args[]) throws SocketException {
            Enumeration nets = NetworkInterface.getNetworkInterfaces();
            for (NetworkInterface netint : Collections.list(nets))
                displayInterfaceInformation(netint);
        }

        static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
            out.printf("Display name: %s\n", netint.getDisplayName());
            out.printf("Name: %s\n", netint.getName());
            Enumeration inetAddresses = netint.getInetAddresses();
            for (InetAddress inetAddress : Collections.list(inetAddresses)) {
                out.printf("InetAddress: %s\n", inetAddress);
            }
            out.printf("\n");
         }
    }  

The following is sample output from the example program:

    Display name: bge0
    Name: bge0
    InetAddress: /fe80:0:0:0:203:baff:fef2:e99d%2
    InetAddress: /121.153.225.59

    Display name: lo0
    Name: lo0
    InetAddress: /0:0:0:0:0:0:0:1%1
    InetAddress: /127.0.0.1


grepsedawk
A: 

Java does not handle multi network systems well. You cannot control which network interface will be returned by InetAddress.getLocalHost(). The only solution I have so far to control which interface is returned by InetAddress.getLocalHost() is to use the security manager and not grant SocketPermission to the addresses that I don't want used.

InetAddress.getAllByName("localhost");

Will get you the loop back addresses.

IntetAddress ia = InetAddress.getLocalHost();

Will get you one of your IP's;

IntetAddress[] iaa = InetAddress.getAllByName(ia.getHostName());

will get you all of the addresses on your host.

The sun InetAddress implements getLocalHost() like this:

public static InetAddress getLocalHost() throws UnknownHostException {

SecurityManager security = System.getSecurityManager();
try {
    String local = impl.getLocalHostName();

    if (security != null) {
 security.checkConnect(local, -1);
    }
    // we are calling getAddressFromNameService directly
    // to avoid getting localHost from cache 

    InetAddress[] localAddrs;
    try {
 localAddrs =
     (InetAddress[]) InetAddress.getAddressFromNameService(local);
    } catch (UnknownHostException uhe) {
 throw new UnknownHostException(local + ": " + uhe.getMessage());
    }
    return localAddrs[0];
} catch (java.lang.SecurityException e) {
    return impl.loopbackAddress();
}

}

Clint
+3  A: 

Do not forget about loopback addresses, which are not visible outside. Here is a function which extracts the first non-loopback IP(IPv4 or IPv6)

private static InetAddress getFirstNonLoopbackAddress(boolean preferIpv4, boolean preferIPv6) throws SocketException {
    Enumeration en = NetworkInterface.getNetworkInterfaces();
    while (en.hasMoreElements()) {
        NetworkInterface i = (NetworkInterface) en.nextElement();
        for (Enumeration en2 = i.getInetAddresses(); en2.hasMoreElements();) {
            InetAddress addr = (InetAddress) en2.nextElement();
            if (!addr.isLoopbackAddress()) {
                if (addr instanceof Inet4Address) {
                    if (preferIPv6) {
                        continue;
                    }
                    return addr;
                }
                if (addr instanceof Inet6Address) {
                    if (preferIpv4) {
                        continue;
                    }
                    return addr;
                }
            }
        }
    }
    return null;
}
adrian.tarau
A: 

solution by @adrian.tarau is nice.

Trilok