12

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

  • What happens when you use InetAddress? – karim79 May 23 '09 at 15:46
  • This is an exact duplicate of the question whose reference I edited into the question. There are many answers there. InetAddress is just fine for cross platform. I have never encountered any problems. – Eddie May 23 '09 at 17:21
  • 1
    If you have multiple NICs and you ask for the "one" IP address of the computer you are on, which IP address you get depends on the binding order of network interfaces on the computer, which depends on a great many variables. I would not rely on it being predictable. – Eddie May 23 '09 at 17:22

6 Answers6

31

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
  • 3,124
  • 2
  • 26
  • 29
13

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<NetworkInterface> 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<InetAddress> 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

Leif Gruenwoldt
  • 13,561
  • 5
  • 60
  • 64
grepsedawk
  • 5,959
  • 5
  • 24
  • 22
  • 3
    To answer the question "why is InetAddress not a good solution?": on linux systems where the hostname is listed as 127.0.0.1 in /etc/hosts, the result is not very useful. On systems where the hostname does not appear in either /etc/hosts or dns, you get an UnknownHostException. On os x, the host name seems to generally resolve well. I don't know what the situation is on windows, but I imagine it works well enough. – Jeremy Huiskamp Feb 10 '11 at 20:22
  • Above code does not work, copy & Paste form here: https://gist.github.com/1225358 –  Sep 18 '11 at 18:29
5

This code worked 4me:

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;


public class ShowIp {

    public static void main(String[] args) throws SocketException {
        NetworkInterface ni = NetworkInterface.getByName("eth0");
        Enumeration<InetAddress> inetAddresses =  ni.getInetAddresses();


        while(inetAddresses.hasMoreElements()) {
            InetAddress ia = inetAddresses.nextElement();
            if(!ia.isLinkLocalAddress()) {
                System.out.println("IP: " + ia.getHostAddress());
            }
        }
    }

}
Bruno
  • 51
  • 1
  • 1
4

It's not ok to just return the first non-loopback interface as it might have been created by some software like Parallels. It's a better bet to try fishing for the eth0.

static private InetAddress getIPv4InetAddress() throws SocketException, UnknownHostException {

    String os = System.getProperty("os.name").toLowerCase();

    if(os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0) {   
        NetworkInterface ni = NetworkInterface.getByName("eth0");

        Enumeration<InetAddress> ias = ni.getInetAddresses();

        InetAddress iaddress;
        do {
            iaddress = ias.nextElement();
        } while(!(iaddress instanceof Inet4Address));

        return iaddress;
    }

    return InetAddress.getLocalHost();  // for Windows and OS X it should work well
}
Maciej Trybiło
  • 1,187
  • 8
  • 20
  • I tried your code not returning my actual ip, i have virtual hosts installed and its returning me one of virtual hosts ip...Also i tried @adrian.tarau solution and that worked like a charm.It actually returned me my local machines IP. – Sagar G. Jul 06 '13 at 06:37
0

The best solution i've found is to run command on linux / ubuntu machine. So I run this command hostname -I | cut -d' ' -f1 using java.

note - second part of method is just to collect the output.

public String getIP() throws IOException
{
    ProcessBuilder pb = new ProcessBuilder("bash", "-c", "hostname -I | cut -d' ' -f1");

    Process process = pb.start();
    InputStream inputStream = process.getInputStream();
    Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8);

    StringBuilder outputString = new StringBuilder();
    while (scanner.hasNextLine())
    {
        synchronized (this)
        {
            String message = scanner.nextLine();
            outputString.append(message);
            outputString.append("\n");
            log(message);
        }
    }
    scanner.close();

    return outputString.toString().trim();
}
Adir Dayan
  • 1,308
  • 13
  • 21
0

The simplest solution in my case was Socket.getLocalAddress(). I had to open the Socket specifically for that purpose, but with all the NetworkInterfaces on my Ubuntu 10.04 machine it was the only way to get the external IP address.

FelixM
  • 1,496
  • 1
  • 9
  • 19