How to get the LAN IP of a client using Java?

18,799

Solution 1

Try java.net.NetworkInterface

import java.net.NetworkInterface;

...

for (
    final Enumeration< NetworkInterface > interfaces =
        NetworkInterface.getNetworkInterfaces( );
    interfaces.hasMoreElements( );
)
{
    final NetworkInterface cur = interfaces.nextElement( );

    if ( cur.isLoopback( ) )
    {
        continue;
    }

    System.out.println( "interface " + cur.getName( ) );

    for ( final InterfaceAddress addr : cur.getInterfaceAddresses( ) )
    {
        final InetAddress inet_addr = addr.getAddress( );

        if ( !( inet_addr instanceof Inet4Address ) )
        {
            continue;
        }

        System.out.println(
            "  address: " + inet_addr.getHostAddress( ) +
            "/" + addr.getNetworkPrefixLength( )
        );

        System.out.println(
            "  broadcast address: " +
                addr.getBroadcast( ).getHostAddress( )
        );
    }
}

Solution 2

At first: There is no single address. Your machine has at least two adresses (127.0.0.1 on "lo" and maybe 192.168.1.1 on "eth1").

You want this: Listing network interfaces

As you may expect, you cannot automatically detect which one is connected to any of your routers, since this needs potentially complex parsing of your routing tables. But if you just want any non-local address this should be enought. To be sure, try to use this at least one time on vista or Windows 7, since they add IPv6 addresses.

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

Solution 3

This is a method I've used for a while. It includes a little hack to figure out the externally visible ip-address as well.

private List<String> getLocalHostAddresses() {

    List<String> addresses = new ArrayList<String>();

    try {
        Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();

        while (e.hasMoreElements()) {
            NetworkInterface ni = e.nextElement();
            Enumeration<InetAddress> e2 = ni.getInetAddresses();
            while (e2.hasMoreElements())
                addresses.add(e2.nextElement().getHostAddress());
        }
        URL u = new URL("http://whatismyip.org");
        BufferedReader in = new BufferedReader(new InputStreamReader(
                u.openStream()));
        addresses.add(in.readLine());
        in.close();
    } catch (Exception ignore) {
    }

    return addresses;
}
Share:
18,799

Related videos on Youtube

cragiz
Author by

cragiz

Updated on June 04, 2022

Comments

  • cragiz
    cragiz almost 2 years

    How can i get the LAN IP-address of a computer using Java? I want the IP-address which is connected to the router and the rest of the network.

    I've tried something like this:

    Socket s = new Socket("www.google.com", 80);
    String ip = s.getLocalAddress().getHostAddress();
    s.close();
    

    This seem to work on some cases, but sometimes it returns the loopback-address or something completely different. Also, it requires internet connection.

    Does anyone got a more accurate method of doing this?

    EDIT: Thought it would be better to ask here than in a comment..

    What if you got many interfaces? For example, one for cable, one for wifi and one for virtual box or so. Is it impossible to actually see which one is connected to the network?

  • cragiz
    cragiz almost 14 years
    what if you got many interfaces? for example, one for cable, one for wifi and one for virtual box or so. is it impossible to acctually see which one is connected to the network?
  • Alexander Pogrebnyak
    Alexander Pogrebnyak almost 14 years
    @Henrik. In that case all of them are connected. It is up to your OS to determine which one will be used for external routing. You can use this Socket constructor java.sun.com/j2se/1.5.0/docs/api/java/net/… to pick up specific local address and port, or construct default socket and bind it to specific interface. Also, check that you can determine information that you need from NetworkInterface object.
  • Alexander Pogrebnyak
    Alexander Pogrebnyak almost 14 years
    @Henrik. Also, because Java has to cater to all OSes you may write a small shell subscript to determine which local interface is a routing interface and pass this information to your Java program, so it can then bind to this specific interface. On the other hand when you connect a Socket this job is done for you, so I suggest you should only do this if you have very specific requirements. From you post it's not clear what those requirements are.
  • Afonso Lage
    Afonso Lage over 5 years
    This return "127.0.0.1" on many machines, so not a valid answer.

Related