Getting the IP address of the current machine using Java
Asked Answered
T

19

347

I am trying to develop a system where there are different nodes that are run on different system or on different ports on the same system.

Now all the nodes create a Socket with a target IP as the IP of a special node known as a bootstrapping node. The nodes then create their own ServerSocket and start listening for connections.

The bootstrapping node maintains a list of Nodes and returns them on being queried.

Now what I need is the node must register its IP to the bootstrapping node. I tried using cli.getInetAddress() once the client connects to the ServerSocket of bootstrapping node but that didn't work.

  1. I need the client to register its PPP IP if available;
  2. Otherwise the LAN IP if available;
  3. Otherwise it must register 127.0.0.1 assuming its the same computer.

Using the code:

System.out.println(Inet4Address.getLocalHost().getHostAddress());

or

System.out.println(InetAddress.getLocalHost().getHostAddress());

My PPP Connection IP address is: 117.204.44.192 but the above returns me 192.168.1.2

EDIT

I am using the following code:

Enumeration e = NetworkInterface.getNetworkInterfaces();
while(e.hasMoreElements())
{
    NetworkInterface n = (NetworkInterface) e.nextElement();
    Enumeration ee = n.getInetAddresses();
    while (ee.hasMoreElements())
    {
        InetAddress i = (InetAddress) ee.nextElement();
        System.out.println(i.getHostAddress());
    }
}

I am able to get all the IP addresses associated all NetworkInterfaces, but how do I distinguish them? This is the output I am getting:

127.0.0.1
192.168.1.2
192.168.56.1
117.204.44.19
Transported answered 28/2, 2012 at 12:26 Comment(8)
Inet4Address.getLocalHost() should work right ?Reprehend
Inside the loop if I add n.isPointToPoint() will that work?? My idea is to return "127.0.0.1" if no Point to Point network is found. Will that work??Transported
@Transported : Please dont' post your genuine IP address. do write 117.xxx.xxx.xxx, for private IP that's okay.Stoneham
@GagandeepBali Thanks for the advice but my IP is a dynamic IP and i get a new IP every time i disconnect and connect my internet. So shouldn't be a problem, I guess.Transported
@Transported Could you please explain the purpose of inner while loop?Mendes
@Mendes the inner while loop is to get all the InetAddresses bound to this particular NetworkInterface. A network interface may be associated with one or more InetAddresses.Transported
@Mendes Try ifconfig -a on a linux distro. Then you see what Network Interface is. That loop iterate those interfacesCarlenecarleton
Related: #6065010Ostensorium
R
178
import java.net.DatagramSocket;
import java.net.InetAddress;

try(final DatagramSocket socket = new DatagramSocket()){
  socket.connect(InetAddress.getByName("8.8.8.8"), 10002);
  ip = socket.getLocalAddress().getHostAddress();
}

This way works well when there are multiple network interfaces. It always returns the preferred outbound IP. The destination 8.8.8.8 is not needed to be reachable.

Connect on a UDP socket has the following effect: it sets the destination for Send/Recv, discards all packets from other addresses, and - which is what we use - transfers the socket into "connected" state, settings its appropriate fields. This includes checking the existence of the route to the destination according to the system's routing table and setting the local endpoint accordingly. The last part seems to be undocumented officially but it looks like an integral trait of Berkeley sockets API (a side effect of UDP "connected" state) that works reliably in both Windows and Linux across versions and distributions.

So, this method will give the local address that would be used to connect to the specified remote host. There is no real connection established, hence the specified remote ip can be unreachable.

Edit:

As @macomgil says, for MacOS you can do this:

Socket socket = new Socket();
socket.connect(new InetSocketAddress("google.com", 80));
System.out.println(socket.getLocalAddress());
Reimers answered 13/7, 2016 at 4:58 Comment(11)
It worked for me on linux but on OsX i get : "0.0.0.0"Imperforate
@Jeef, answer is updated. If it doesnt work on OsX, then you need pick another way.Reimers
Brilliant! FYI, when dealing with closed inner network, just replace 8.8.8.8 with something every host can reachJingo
Works on Windows; can we confirm if OSX is still a problem?Leora
Does not work in version 1.6 or earlier, in case you've got some older code you're not willing to shift to a newer build target.Entoil
"discards all packets from other addresses" what does this line means ?Elwaine
@Leora I'm still getting 0.0.0.0 on OSXEffieeffigy
"0.0.0.0" on IBM i as wellAttis
Why do I get 192.168.0.5 for both approaches?Flamboyant
@PeterTutervai, did you get any solution for 0.0.0.0?Noninterference
Using OpenJDK 17 on MacOS 13.2.1 (Ventura), this returns the the "site-local" address (eg, 192.168.86.44) as expected.Cultigen
K
304

This could be a bit tricky in the most general case.

On the face of it, InetAddress.getLocalHost() should give you the IP address of this host. The problem is that a host could have lots of network interfaces, and an interface could be bound to more than one IP address. And to top that, not all IP addresses will be reachable outside of your machine or your LAN. For example, they could be IP addresses for virtual network devices, private network IP addresses, and so on.

What this means is that the IP address returned by InetAddress.getLocalHost() might not be the right one to use.

How can you deal with this?

  • One approach is to use NetworkInterface.getNetworkInterfaces() to get all of the known network interfaces on the host, and then iterate over each NI's addresses.
  • Another approach is to (somehow) get the externally advertized FQDN for the host, and use InetAddress.getByName() to look up the primary IP address. (But how do you get it, and how do you deal with a DNS-based load balancer?)
  • A variation of the previous is to get the preferred FQDN from a config file or a command line parameter.
  • Another variation is to get the preferred IP address from a config file or a command line parameter.

In summary, InetAddress.getLocalHost() will typically work, but you may need to provide an alternative method for the cases where your code is run in an environment with "complicated" networking.


I am able to get all the IP addresses associated all Network Interfaces, but how do i distinguish them?

  • Any address in the range 127.xxx.xxx.xxx is a "loopback" address. It is only visible to "this" host.
  • Any address in the range 192.168.xxx.xxx is a private (aka site local) IP address. These are reserved for use within an organization. The same applies to 10.xxx.xxx.xxx addresses, and 172.16.xxx.xxx through 172.31.xxx.xxx.
  • Addresses in the range 169.254.xxx.xxx are link local IP addresses. These are reserved for use on a single network segment.
  • Addresses in the range 224.xxx.xxx.xxx through 239.xxx.xxx.xxx are multicast addresses.
  • The address 255.255.255.255 is the broadcast address.
  • Anything else should be a valid public point-to-point IPv4 address.

In fact, the InetAddress API provides methods for testing for loopback, link local, site local, multicast and broadcast addresses. You can use these to sort out which of the IP addresses you get back is most appropriate.

Kristelkristen answered 28/2, 2012 at 12:59 Comment(3)
In case anyone is curious, getLocalHost essentially does a DNS lookup on the server's hostname. If it gets an IP address from that lookup then it searches through the interfaces available to see which interface has that IP address and it returns that interface. This means getLocalHost will tend to work in a "server" environment where the outgoing IP is the one that maps to the server's hostname.Minutia
On Ubuntu 14.04 this api returns 127.0.1.1 even though ifconfig only reports two interfaces, the one I want (the publicly accessible ip address), and loopback (127.0.0.1). Weird that it returns a different loopback alias.Dyslalia
I'll add that if you use getLocalHost().getHostAddress() to publish something, you may see 0.0.0.0 when looking from a nother computer on the network. This is explained here This is what happened to me when i was using Gazebo across two computersJeminah
R
178
import java.net.DatagramSocket;
import java.net.InetAddress;

try(final DatagramSocket socket = new DatagramSocket()){
  socket.connect(InetAddress.getByName("8.8.8.8"), 10002);
  ip = socket.getLocalAddress().getHostAddress();
}

This way works well when there are multiple network interfaces. It always returns the preferred outbound IP. The destination 8.8.8.8 is not needed to be reachable.

Connect on a UDP socket has the following effect: it sets the destination for Send/Recv, discards all packets from other addresses, and - which is what we use - transfers the socket into "connected" state, settings its appropriate fields. This includes checking the existence of the route to the destination according to the system's routing table and setting the local endpoint accordingly. The last part seems to be undocumented officially but it looks like an integral trait of Berkeley sockets API (a side effect of UDP "connected" state) that works reliably in both Windows and Linux across versions and distributions.

So, this method will give the local address that would be used to connect to the specified remote host. There is no real connection established, hence the specified remote ip can be unreachable.

Edit:

As @macomgil says, for MacOS you can do this:

Socket socket = new Socket();
socket.connect(new InetSocketAddress("google.com", 80));
System.out.println(socket.getLocalAddress());
Reimers answered 13/7, 2016 at 4:58 Comment(11)
It worked for me on linux but on OsX i get : "0.0.0.0"Imperforate
@Jeef, answer is updated. If it doesnt work on OsX, then you need pick another way.Reimers
Brilliant! FYI, when dealing with closed inner network, just replace 8.8.8.8 with something every host can reachJingo
Works on Windows; can we confirm if OSX is still a problem?Leora
Does not work in version 1.6 or earlier, in case you've got some older code you're not willing to shift to a newer build target.Entoil
"discards all packets from other addresses" what does this line means ?Elwaine
@Leora I'm still getting 0.0.0.0 on OSXEffieeffigy
"0.0.0.0" on IBM i as wellAttis
Why do I get 192.168.0.5 for both approaches?Flamboyant
@PeterTutervai, did you get any solution for 0.0.0.0?Noninterference
Using OpenJDK 17 on MacOS 13.2.1 (Ventura), this returns the the "site-local" address (eg, 192.168.86.44) as expected.Cultigen
P
61

Posting here tested IP ambiguity workaround code from https://issues.apache.org/jira/browse/JCS-40 (InetAddress.getLocalHost() ambiguous on Linux systems):

/**
 * Returns an <code>InetAddress</code> object encapsulating what is most likely the machine's LAN IP address.
 * <p/>
 * This method is intended for use as a replacement of JDK method <code>InetAddress.getLocalHost</code>, because
 * that method is ambiguous on Linux systems. Linux systems enumerate the loopback network interface the same
 * way as regular LAN network interfaces, but the JDK <code>InetAddress.getLocalHost</code> method does not
 * specify the algorithm used to select the address returned under such circumstances, and will often return the
 * loopback address, which is not valid for network communication. Details
 * <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4665037">here</a>.
 * <p/>
 * This method will scan all IP addresses on all network interfaces on the host machine to determine the IP address
 * most likely to be the machine's LAN address. If the machine has multiple IP addresses, this method will prefer
 * a site-local IP address (e.g. 192.168.x.x or 10.10.x.x, usually IPv4) if the machine has one (and will return the
 * first site-local address if the machine has more than one), but if the machine does not hold a site-local
 * address, this method will return simply the first non-loopback address found (IPv4 or IPv6).
 * <p/>
 * If this method cannot find a non-loopback address using this selection algorithm, it will fall back to
 * calling and returning the result of JDK method <code>InetAddress.getLocalHost</code>.
 * <p/>
 *
 * @throws UnknownHostException If the LAN address of the machine cannot be found.
 */
private static InetAddress getLocalHostLANAddress() throws UnknownHostException {
    try {
        InetAddress candidateAddress = null;
        // Iterate all NICs (network interface cards)...
        for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {
            NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
            // Iterate all IP addresses assigned to each card...
            for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
                InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
                if (!inetAddr.isLoopbackAddress()) {

                    if (inetAddr.isSiteLocalAddress()) {
                        // Found non-loopback site-local address. Return it immediately...
                        return inetAddr;
                    }
                    else if (candidateAddress == null) {
                        // Found non-loopback address, but not necessarily site-local.
                        // Store it as a candidate to be returned if site-local address is not subsequently found...
                        candidateAddress = inetAddr;
                        // Note that we don't repeatedly assign non-loopback non-site-local addresses as candidates,
                        // only the first. For subsequent iterations, candidate will be non-null.
                    }
                }
            }
        }
        if (candidateAddress != null) {
            // We did not find a site-local address, but we found some other non-loopback address.
            // Server might have a non-site-local address assigned to its NIC (or it might be running
            // IPv6 which deprecates the "site-local" concept).
            // Return this non-loopback candidate address...
            return candidateAddress;
        }
        // At this point, we did not find a non-loopback address.
        // Fall back to returning whatever InetAddress.getLocalHost() returns...
        InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
        if (jdkSuppliedAddress == null) {
            throw new UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null.");
        }
        return jdkSuppliedAddress;
    }
    catch (Exception e) {
        UnknownHostException unknownHostException = new UnknownHostException("Failed to determine LAN address: " + e);
        unknownHostException.initCause(e);
        throw unknownHostException;
    }
}
Picaroon answered 6/12, 2013 at 7:54 Comment(3)
It must be noted that this still doesn't resolve ambuguity in case host has multiple similar nerwork interfaces.Picaroon
the bellow answer is better - #9482365 gets the local ip address that is used as src for Default GatwayImperforate
Why ip address is added with front slash ..? like /10.39.0.17 ..?, Is it always this way should be trimmed ..?Goodale
P
57

You can use java's InetAddress class for this purpose.

InetAddress IP=InetAddress.getLocalHost();
System.out.println("IP of my system is := "+IP.getHostAddress());

Output for my system = IP of my system is := 10.100.98.228

getHostAddress() returns

Returns the IP address string in textual presentation.

OR you can also do

InetAddress IP=InetAddress.getLocalHost();
System.out.println(IP.toString());

Output = IP of my system is := RanRag-PC/10.100.98.228

Potation answered 28/2, 2012 at 12:30 Comment(3)
Note that 10.x.x.x is a private address, indicating that your system is on a NAT network. It will appear as a different address when contacting the outside world. If you truly need the external IP address, you'll have to contact one of many sites which will echo back to you the IP address you're coming from. This may or may not be useful to you. Your system will almost surely not be reachable from the outside in any event.Anon
Omg this is save my life. Previous I use clientSocket.getInetAddress().getHostName();Escarpment
This solution does not work on Linux system.Obeah
K
28

When you are looking for your "local" address, you should note that each machine has not only a single network interface, and each interface could have its own local address. Which means your machine is always owning several "local" addresses.

Different "local" addresses will be automatically chosen to use when you are connecting to different endpoints. For example, when you connect to google.com, you are using an "outside" local address; but when you connect to your localhost, your local address is always localhost itself, because localhost is just a loopback.

Below is showing how to find out your local address when you are communicating with google.com:

Socket socket = new Socket();
socket.connect(new InetSocketAddress("google.com", 80));
System.out.println(socket.getLocalAddress());
socket.close();
Kinelski answered 24/1, 2017 at 7:12 Comment(2)
Awesome !! - so easy :)Dorian
add socket.close() at the end :)Latrena
P
12

Example in scala (useful in sbt file):

  import collection.JavaConverters._
  import java.net._

  def getIpAddress: String = {

    val enumeration = NetworkInterface.getNetworkInterfaces.asScala.toSeq

    val ipAddresses = enumeration.flatMap(p =>
      p.getInetAddresses.asScala.toSeq
    )

    val address = ipAddresses.find { address =>
      val host = address.getHostAddress
      host.contains(".") && !address.isLoopbackAddress
    }.getOrElse(InetAddress.getLocalHost)

    address.getHostAddress
  }
Publish answered 9/7, 2014 at 8:59 Comment(0)
S
10

EDIT 1: Updated code, since the previous link, exists no more

import java.io.*;
import java.net.*;

public class GetMyIP {
    public static void main(String[] args) {
        URL url = null;
        BufferedReader in = null;
        String ipAddress = "";
        try {
            url = new URL("http://bot.whatismyipaddress.com");
            in = new BufferedReader(new InputStreamReader(url.openStream()));
            ipAddress = in.readLine().trim();
            /* IF not connected to internet, then
             * the above code will return one empty
             * String, we can check it's length and
             * if length is not greater than zero, 
             * then we can go for LAN IP or Local IP
             * or PRIVATE IP
             */
            if (!(ipAddress.length() > 0)) {
                try {
                    InetAddress ip = InetAddress.getLocalHost();
                    System.out.println((ip.getHostAddress()).trim());
                    ipAddress = (ip.getHostAddress()).trim();
                } catch(Exception exp) {
                    ipAddress = "ERROR";
                }
            }
        } catch (Exception ex) {
            // This try will give the Private IP of the Host.
            try {
                InetAddress ip = InetAddress.getLocalHost();
                System.out.println((ip.getHostAddress()).trim());
                ipAddress = (ip.getHostAddress()).trim();
            } catch(Exception exp) {
                ipAddress = "ERROR";
            }
            //ex.printStackTrace();
        }
        System.out.println("IP Address: " + ipAddress);
    }
}

ACTUAL VERSION: This stopped working

Hopefully this snippet might help you to achieve this :

// Method to get the IP Address of the Host.
private String getIP()
{
    // This try will give the Public IP Address of the Host.
    try
    {
        URL url = new URL("http://automation.whatismyip.com/n09230945.asp");
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String ipAddress = new String();
        ipAddress = (in.readLine()).trim();
        /* IF not connected to internet, then
         * the above code will return one empty
         * String, we can check it's length and
         * if length is not greater than zero, 
         * then we can go for LAN IP or Local IP
         * or PRIVATE IP
         */
        if (!(ipAddress.length() > 0))
        {
            try
            {
                InetAddress ip = InetAddress.getLocalHost();
                System.out.println((ip.getHostAddress()).trim());
                return ((ip.getHostAddress()).trim());
            }
            catch(Exception ex)
            {
                return "ERROR";
            }
        }
        System.out.println("IP Address is : " + ipAddress);

        return (ipAddress);
    }
    catch(Exception e)
    {
        // This try will give the Private IP of the Host.
        try
        {
            InetAddress ip = InetAddress.getLocalHost();
            System.out.println((ip.getHostAddress()).trim());
            return ((ip.getHostAddress()).trim());
        }
        catch(Exception ex)
        {
            return "ERROR";
        }
    }
}
Stoneham answered 28/2, 2012 at 17:21 Comment(8)
The solution would work, hopefully if i am always connected to the internet, but i am not guaranteed that. Besides, when the system is not connected to the internet and then I need to return the LAN IP address of the system if any, otherwise the localhost. So not a feasible option for me. Any other way??Transported
@Transported : When you are connected to the Internet, only then you be having your public IP I guess, if you are not connected then this method will give you, your local IP or LAN IP, and for the last condition as specified by you you can return "127.0.0.1", instead of returning Error.Stoneham
Theoretically looks fine but i have the following IPs on my system 127.0.0.1 -> localhost 192.168.1.2 -> The IP assigned by my modem (Ethernet Adapter Local Area Connection) 192.168.56.1 -> Virtual-box (Ethernet Adapter Virtual-box Host-only Network) 117.204.44.19 -> My actual IP connected to the internet (PPP adapter dataone) I am basically not connected to any LAN. But if i disconnect my internet. It returns me 192.168.1.2 instead of 127.0.0.1 So it is typically important to explore the NetworkInterface I guessTransported
See If I modify my code as done in my latest edit, If I am connected to the internet I get my Public IP Address, but if I am not I get my Private IP or Local IP or LAN IP, as 192.168.2.1, you can modify the checks to suit your needs, in the above code.Stoneham
Still doesn't work, tested your code on variety of environments. It sometimes returns the IP addresses that are not reachable off the system, like addresses to virtual machines.Transported
I like your approach but that link seems not to work anymore!! Can I put a controller on my own system to work instead of that external link and so be more reliable???Ine
@Bludream: Thankyou so much, for bringing this to my knowledge, that the link is not working anymore. I have updated the post, with some new inputs. Hopefully it works for your usercase. Regarding your question, I really don't know, how to setup a controller on your own system to make it work. So I won't be able to give insight on this topic, MY BAD. Thanks again and KEEP SMILING :-)Stoneham
As much as this is a cool solution, It is extremely unreliable. If you were to block the main thread (lets say) and for whatever reason whatismyip.com was down for some length of time, your app would also be down :(. Or it will return garbage data and cause unexpected behavior. Also, this returns the outter most IP address detectable by whatismyip.com, not necessarily the ip address of the machine you're using.Geosyncline
C
9
private static InetAddress getLocalAddress(){
        try {
            Enumeration<NetworkInterface> b = NetworkInterface.getNetworkInterfaces();
            while( b.hasMoreElements()){
                for ( InterfaceAddress f : b.nextElement().getInterfaceAddresses())
                    if ( f.getAddress().isSiteLocalAddress())
                        return f.getAddress();
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return null;
    }
Clippard answered 3/11, 2014 at 6:52 Comment(1)
please, consider add some explanation about what your code does.Sofko
C
6

You can use java.net.InetAddress API. Try this :

InetAddress.getLocalHost().getHostAddress();
Contortionist answered 28/2, 2012 at 12:30 Comment(2)
it just will return 127.0.0.1Sofko
Redundant answer: https://mcmap.net/q/11202/-getting-the-ip-address-of-the-current-machine-using-java says the same thing.Kristelkristen
D
6

firstly import the class

import java.net.InetAddress;

in class

  InetAddress iAddress = InetAddress.getLocalHost();
  String currentIp = iAddress.getHostAddress();
  System.out.println("Current IP address : " +currentIp); //gives only host address
Dichotomous answered 12/8, 2014 at 6:19 Comment(1)
it gives only the first ip address even if it's not the one in use!Jerad
G
4

This is a working example of the ACCEPTED answer above! This NetIdentity class will store both the internal host ip, as well as the local loopback. If you're on a DNS based server, as mentioned above, you may need to add some more checks, or possible go the Configuration File Route.

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

/**
 * Class that allows a device to identify itself on the INTRANET.
 * 
 * @author Decoded4620 2016
 */
public class NetIdentity {

    private String loopbackHost = "";
    private String host = "";

    private String loopbackIp = "";
    private String ip = "";
    public NetIdentity(){

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

            while(interfaces.hasMoreElements()){
                NetworkInterface i = interfaces.nextElement();
                if(i != null){
                    Enumeration<InetAddress> addresses = i.getInetAddresses();
                    System.out.println(i.getDisplayName());
                    while(addresses.hasMoreElements()){
                        InetAddress address = addresses.nextElement();
                        String hostAddr = address.getHostAddress();

                        // local loopback
                        if(hostAddr.indexOf("127.") == 0 ){
                            this.loopbackIp = address.getHostAddress();
                            this.loopbackHost = address.getHostName();
                        }

                        // internal ip addresses (behind this router)
                        if( hostAddr.indexOf("192.168") == 0 || 
                                hostAddr.indexOf("10.") == 0 || 
                                hostAddr.indexOf("172.16") == 0 ){
                            this.host = address.getHostName();
                            this.ip = address.getHostAddress();
                        }


                        System.out.println("\t\t-" + address.getHostName() + ":" + address.getHostAddress() + " - "+ address.getAddress());
                    }
                }
            }
        }
        catch(SocketException e){

        }
        try{
            InetAddress loopbackIpAddress = InetAddress.getLocalHost();
            this.loopbackIp = loopbackIpAddress.getHostName();
            System.out.println("LOCALHOST: " + loopbackIp);
        }
        catch(UnknownHostException e){
            System.err.println("ERR: " + e.toString());
        }
    }

    public String getLoopbackHost(){
        return loopbackHost;
    }

    public String getHost(){
        return host;
    }
    public String getIp(){
        return ip;
    }
    public String getLoopbackIp(){
        return loopbackIp;
    }
}

When I run this code I actually get a print out like this:

    Software Loopback Interface 1
        -127.0.0.1:127.0.0.1 - [B@19e1023e
        -0:0:0:0:0:0:0:1:0:0:0:0:0:0:0:1 - [B@7cef4e59
Broadcom 802.11ac Network Adapter
        -VIKING.yourisp.com:192.168.1.142 - [B@64b8f8f4
        -fe80:0:0:0:81fa:31d:21c9:85cd%wlan0:fe80:0:0:0:81fa:31d:21c9:85cd%wlan0 - [B@2db0f6b2
Microsoft Kernel Debug Network Adapter
Intel Edison USB RNDIS Device
Driver for user-mode network applications
Cisco Systems VPN Adapter for 64-bit Windows
VirtualBox Host-Only Ethernet Adapter
        -VIKING:192.168.56.1 - [B@3cd1f1c8
        -VIKING:fe80:0:0:0:d599:3cf0:5462:cb7%eth4 - [B@3a4afd8d
LogMeIn Hamachi Virtual Ethernet Adapter
        -VIKING:25.113.118.39 - [B@1996cd68
        -VIKING:2620:9b:0:0:0:0:1971:7627 - [B@3339ad8e
        -VIKING:fe80:0:0:0:51bf:994d:4656:8486%eth5 - [B@555590
Bluetooth Device (Personal Area Network)
        -fe80:0:0:0:4c56:8009:2bca:e16b%eth6:fe80:0:0:0:4c56:8009:2bca:e16b%eth6 - [B@3c679bde
Bluetooth Device (RFCOMM Protocol TDI)
Intel(R) Ethernet Connection (2) I218-V
        -fe80:0:0:0:4093:d169:536c:7c7c%eth7:fe80:0:0:0:4093:d169:536c:7c7c%eth7 - [B@16b4a017
Microsoft Wi-Fi Direct Virtual Adapter
        -fe80:0:0:0:103e:cdf0:c0ac:1751%wlan1:fe80:0:0:0:103e:cdf0:c0ac:1751%wlan1 - [B@8807e25
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0000
VirtualBox Host-Only Ethernet Adapter-WFP Native MAC Layer LightWeight Filter-0000
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0001
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0002
VirtualBox Host-Only Ethernet Adapter-VirtualBox NDIS Light-Weight Filter-0000
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0003
VirtualBox Host-Only Ethernet Adapter-QoS Packet Scheduler-0000
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0004
VirtualBox Host-Only Ethernet Adapter-WFP 802.3 MAC Layer LightWeight Filter-0000
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0005
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0000
Intel(R) Ethernet Connection (2) I218-V-WFP Native MAC Layer LightWeight Filter-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0001
Intel(R) Ethernet Connection (2) I218-V-Shrew Soft Lightweight Filter-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0002
Intel(R) Ethernet Connection (2) I218-V-VirtualBox NDIS Light-Weight Filter-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0003
Intel(R) Ethernet Connection (2) I218-V-QoS Packet Scheduler-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0004
Intel(R) Ethernet Connection (2) I218-V-WFP 802.3 MAC Layer LightWeight Filter-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0005
Broadcom 802.11ac Network Adapter-WFP Native MAC Layer LightWeight Filter-0000
Broadcom 802.11ac Network Adapter-Virtual WiFi Filter Driver-0000
Broadcom 802.11ac Network Adapter-Native WiFi Filter Driver-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0003
Broadcom 802.11ac Network Adapter-Shrew Soft Lightweight Filter-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0004
Broadcom 802.11ac Network Adapter-VirtualBox NDIS Light-Weight Filter-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0005
Broadcom 802.11ac Network Adapter-QoS Packet Scheduler-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0006
Broadcom 802.11ac Network Adapter-WFP 802.3 MAC Layer LightWeight Filter-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0007
Microsoft Wi-Fi Direct Virtual Adapter-WFP Native MAC Layer LightWeight Filter-0000
Microsoft Wi-Fi Direct Virtual Adapter-Native WiFi Filter Driver-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0002
Microsoft Wi-Fi Direct Virtual Adapter-Shrew Soft Lightweight Filter-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0003
Microsoft Wi-Fi Direct Virtual Adapter-VirtualBox NDIS Light-Weight Filter-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0004
Microsoft Wi-Fi Direct Virtual Adapter-QoS Packet Scheduler-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0005
Microsoft Wi-Fi Direct Virtual Adapter-WFP 802.3 MAC Layer LightWeight Filter-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0006

For my use I'm setting up a Upnp Server, it helped to understand the 'pattern' that i was looking for. Some of the objects returned are Ethernet Adapters, Network Adapters, Virtual Network Adapters, Drivers, and VPN Client Adapters. Not everything has an Address either. So you'll want to skip out on interface objects that don't.

You can also add this to the loop for the current NetworkInterface i

while(interfaces.hasMoreElements()){
    Enumeration<InetAddress> addresses = i.getInetAddresses();
    System.out.println(i.getDisplayName());
    System.out.println("\t- name:" + i.getName());
    System.out.println("\t- idx:" + i.getIndex());
    System.out.println("\t- max trans unit (MTU):" + i.getMTU());
    System.out.println("\t- is loopback:" + i.isLoopback());
    System.out.println("\t- is PPP:" + i.isPointToPoint());
    System.out.println("\t- isUp:" + i.isUp());
    System.out.println("\t- isVirtual:" + i.isVirtual());
    System.out.println("\t- supportsMulticast:" + i.supportsMulticast());
}

And You'll see information in your output much like this:

Software Loopback Interface 1
    - name:lo
    - idx:1
    - max trans unit (MTU):-1
    - is loopback:true
    - is PPP:false
    - isUp:true
    - isVirtual:false
    - supportsMulticast:true
        -ADRESS: [127.0.0.1(VIKING-192.168.56.1)]127.0.0.1:127.0.0.1 - [B@19e1023e
        -ADRESS: [0:0:0:0:0:0:0:1(VIKING-192.168.56.1)]0:0:0:0:0:0:0:1:0:0:0:0:0:0:0:1 - [B@7cef4e59
Broadcom 802.11ac Network Adapter
    - name:wlan0
    - idx:2
    - max trans unit (MTU):1500
    - is loopback:false
    - is PPP:false
    - isUp:true
    - isVirtual:false
    - supportsMulticast:true
        -ADRESS: [VIKING.monkeybrains.net(VIKING-192.168.56.1)]VIKING.monkeybrains.net:192.168.1.142 - [B@64b8f8f4
        -ADRESS: [fe80:0:0:0:81fa:31d:21c9:85cd%wlan0(VIKING-192.168.56.1)]fe80:0:0:0:81fa:31d:21c9:85cd%wlan0:fe80:0:0:0:81fa:31d:21c9:85cd%wlan0 - [B@2db0f6b2
Microsoft Kernel Debug Network Adapter
    - name:eth0
    - idx:3
    - max trans unit (MTU):-1
    - is loopback:false
    - is PPP:false
    - isUp:false
    - isVirtual:false
    - supportsMulticast:true
Geosyncline answered 19/2, 2016 at 23:0 Comment(0)
A
3

Use InetAddress.getLocalHost() to get the local address

import java.net.InetAddress;

try {
  InetAddress addr = InetAddress.getLocalHost();            
  System.out.println(addr.getHostAddress());
} catch (UnknownHostException e) {
}
Adna answered 28/2, 2012 at 12:32 Comment(3)
My PPP Connection Ip address is: 117.204.44.192 But the above returns me 192.168.1.2Transported
You need to crawl all the InetAddress instances available and figure out which is the proper one.Geosyncline
Redundant answer: https://mcmap.net/q/11202/-getting-the-ip-address-of-the-current-machine-using-java says the same thing.Kristelkristen
Q
2

Your computer can have multiple NetworkInterfaces, each with multiple InetAddresses. If you filter out any local addresses, the reminder of the addresses are the non-local ones, of which you can have one, none or many.

Unfortunately the networking API in Java still uses the (old) Enumerations instead of Iterators and Streams, which we can counter by wrapping them as streams. So all we need to do is

  • stream over all network interfaces and their addresses, and
  • filter out the local ones

Code:

private Stream<InetAddress> getNonLocalIpAddresses() throws IOException {
    return enumerationAsStream(NetworkInterface.getNetworkInterfaces())
        .flatMap(networkInterface -> enumerationAsStream(networkInterface.getInetAddresses()))
        .filter(inetAddress -> !inetAddress.isAnyLocalAddress())
        .filter(inetAddress -> !inetAddress.isSiteLocalAddress())
        .filter(inetAddress -> !inetAddress.isLoopbackAddress())
        .filter(inetAddress -> !inetAddress.isLinkLocalAddress());
}

On my machine, this currently returns two IPv6 addresses.

To get the first of these InetAdresses:

private String getMyIp() throws IOException {
    return getNonLocalIpAddresses()
        .map(InetAddress::getHostAddress)
        .findFirst()
        .orElseThrow(NoSuchElementException::new);
}

Method that wraps Enumerations as Streams:

public static <T> Stream<T> enumerationAsStream(Enumeration<T> e) {
    return StreamSupport.stream(
        Spliterators.spliteratorUnknownSize(
            new Iterator<>() {
                public T next() { return e.nextElement();  }
                public boolean hasNext() { return e.hasMoreElements(); }
            }, Spliterator.ORDERED), false);
}
Qualification answered 23/12, 2021 at 14:36 Comment(1)
Since Java 9, enumarationAsStream can be more compact: public static <T> Stream<T> enumerationAsStream(Enumeration<T> e) { return StreamSupport.stream(Spliterators.spliteratorUnknownSize(e.asIterator(), Spliterator.ORDERED), false); } Thirtythree
A
1
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class IpAddress {

NetworkInterface ifcfg;
Enumeration<InetAddress> addresses;
String address;

public String getIpAddress(String host) {
    try {
        ifcfg = NetworkInterface.getByName(host);
        addresses = ifcfg.getInetAddresses();
        while (addresses.hasMoreElements()) {
            address = addresses.nextElement().toString();
            address = address.replace("/", "");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ifcfg.toString();
}
}
Absorptance answered 25/7, 2014 at 4:11 Comment(0)
U
1

A rather simplistic approach that seems to be working...

String getPublicIPv4() throws UnknownHostException, SocketException{
    Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
    String ipToReturn = null;
    while(e.hasMoreElements())
    {
        NetworkInterface n = (NetworkInterface) e.nextElement();
        Enumeration<InetAddress> ee = n.getInetAddresses();
        while (ee.hasMoreElements())
        {
            InetAddress i = (InetAddress) ee.nextElement();
            String currentAddress = i.getHostAddress();
            logger.trace("IP address "+currentAddress+ " found");
            if(!i.isSiteLocalAddress()&&!i.isLoopbackAddress() && validate(currentAddress)){
                ipToReturn = currentAddress;    
            }else{
                System.out.println("Address not validated as public IPv4");
            }

        }
    }

    return ipToReturn;
}

private static final Pattern IPv4RegexPattern = Pattern.compile(
        "^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");

public static boolean validate(final String ip) {
    return IPv4RegexPattern.matcher(ip).matches();
}
Urger answered 5/1, 2016 at 11:38 Comment(0)
L
1

A Kotlin example that works, at least for Windows, even when my VPN is turned on. (Other methods seemed to fail when the VPN was turned on) It involves looking up the IP address of the computer just once. From then on the IP address can always be found from stored adapter information.

import java.net.NetworkInterface
import java.util.prefs.Preferences

class WindowsIP {
    companion object {
        val prefs = Preferences.userNodeForPackage(this::class.java)  //Get the current IP address for the wifi adapter whose information
        // has been stored by calling findWifiAdapter(currentIp) with the known current IP (from wifi properties or whatever)
        fun getIpAddress(): String {
            val wlanName = prefs.get("WlanName", "")
            val wlanDisplName = prefs.get("WlanDisplName", "")
            val addrCnt = prefs.getInt("wlanAddrCount", 0)
            val nis = NetworkInterface.getNetworkInterfaces()
            for (ni in nis) {
                if (ni.name == wlanName && ni.displayName == wlanDisplName) {
                    var count = 0
                    for (addr in ni.inetAddresses) {
                        if (count++ == addrCnt) {
                            return addr.hostAddress
                        }
                    }
                }
            }
            return "Unknown. Call findWifiAdapter() with current IP address"
        }

        fun findWifiAdapter(currentIP: String) {  //Find the wifi adapter using the current IP address and store the information
                val nis = NetworkInterface.getNetworkInterfaces()
                for(ni in nis) {
                    var count = 0;
                    for(adr in ni.inetAddresses) {
                        if(adr.hostAddress == currentIP) {
                            prefs.put("WlanName", ni.name)
                            prefs.put("WlanDisplName", ni.displayName)
                            prefs.putInt("wlanAddrCount", count)  //Probably always zero?
                        }
                        ++count
                    }
                }
        }
    }
}
Logomachy answered 14/1, 2023 at 5:30 Comment(0)
M
0

Usually when i try to find my public IP Address like cmyip.com or www.iplocation.net, i use this way:

public static String myPublicIp() {

    /*nslookup myip.opendns.com resolver1.opendns.com*/
    String ipAdressDns  = "";
    try {
        String command = "nslookup myip.opendns.com resolver1.opendns.com";
        Process proc = Runtime.getRuntime().exec(command);

        BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));

        String s;
        while ((s = stdInput.readLine()) != null) {
            ipAdressDns  += s + "\n";
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return ipAdressDns ;
}
Marasmus answered 18/12, 2016 at 12:59 Comment(0)
A
0

This gets the IP address of your network if your machine is part of a network

try {
    System.out.println(InetAddress.getLocalHost().getHostAddress());
} catch (UnknownHostException e) {
    e.printStackTrace();
}
Asinine answered 10/7, 2019 at 20:11 Comment(1)
Redundant answer. Other (earlier) answers say the same thing.Kristelkristen
F
0

Since my system (like so many other systems) had various network interfaces.InetAddress.getLocalHost() or Inet4Address.getLocalHost() simply returned one that I did not desire. Therefore I had to use this naive approach.

InetAddress[] allAddresses = Inet4Address.getAllByName("YourComputerHostName");
        InetAddress desiredAddress;
        //In order to find the desired Ip to be routed by other modules (WiFi adapter)
        for (InetAddress address :
                allAddresses) {
            if (address.getHostAddress().startsWith("192.168.2")) {
                desiredAddress = address;
            }
        }
// Use the desired address for whatever purpose.

Just be careful that in this approach I already knew that my desired IP address is in 192.168.2 subnet.

Fernyak answered 10/4, 2020 at 0:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.