Java getting my IP address
Asked Answered
B

10

38

I am trying to get my Internet IP address in Java but I keep getting my local address (ie: 127.0.0.1), when my IP address is 192.168.0.xxx

I am using the line:

InetAddress.getLocalHost().getHostAddress();

which seems standard to get the IP address, but it is not what I am looking for. Every tutorial says to use this line, so I am a little confused.

Could anyone please let me know how I can get my correct IP address please?


I'm running on a device that is connected to WiFi, and I'm not using any cable. I am connecting to a server using the IP given by ifconfig inet addr, and I am looking to get the device's inet addr. I could check the IP of the socket on the server side, but thought it'd be nicer if the device (client) tells the server which IP he is expecting other devices to connect on.

Bobbette answered 10/11, 2011 at 17:9 Comment(7)
Is it possible you're connecting to the server through the localhost? Is this code running on the server, or a desktop app, or what?Floodgate
What is "the IP address"? My computer currently has at least five.Cawnpore
Hmm from the docs: If there is a security manager, its checkConnect method is called with the local host name and -1 as its arguments to see if the operation is allowed. If the operation is not allowed, an InetAddress representing the loopback address is returned.Floodgate
I'm running on a device that is connected to WiFi, and I'm not using any cable. I am connecting to a server using the IP given by ifconfig inet addr, and I am looking to get the device's inet addr.Bobbette
I could check the IP of the socket on the server side but thought it'd be nicer if the device (client) tells the server which IP he is expecting other devices to connect on.Bobbette
#494965Ashelman
Maybe I should just have the server call getRemoteSocketAddress().toString(); on the client's socket and not try to have the client look for his own IP.Bobbette
S
24

The NetworkInterface class contains all the relevant methods, but be aware that there's no such thing as "my IP". A machine can have multiple interfaces and each interface can have multiple IPs.

You can list them all with this class but which interface and IP you choose from the list depends on what you exactly need to use this IP for.

(InetAddress.getLocalHost() doesn't consult your interfaces, it simply returns constant 127.0.0.1 (for IPv4))

Serval answered 10/11, 2011 at 17:13 Comment(0)
C
57
    String ip;
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface iface = interfaces.nextElement();
            // filters out 127.0.0.1 and inactive interfaces
            if (iface.isLoopback() || !iface.isUp())
                continue;

            Enumeration<InetAddress> addresses = iface.getInetAddresses();
            while(addresses.hasMoreElements()) {
                InetAddress addr = addresses.nextElement();
                ip = addr.getHostAddress();
                System.out.println(iface.getDisplayName() + " " + ip);
            }
        }
    } catch (SocketException e) {
        throw new RuntimeException(e);
    }
Cockneyism answered 16/1, 2013 at 17:30 Comment(0)
S
24

The NetworkInterface class contains all the relevant methods, but be aware that there's no such thing as "my IP". A machine can have multiple interfaces and each interface can have multiple IPs.

You can list them all with this class but which interface and IP you choose from the list depends on what you exactly need to use this IP for.

(InetAddress.getLocalHost() doesn't consult your interfaces, it simply returns constant 127.0.0.1 (for IPv4))

Serval answered 10/11, 2011 at 17:13 Comment(0)
N
17

Let's ask AWS

URL url = new URL("http://checkip.amazonaws.com/");
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
System.out.println(br.readLine());

EDIT

Before you downvote, I'm well aware this is not a java solution. Its a general solution for any programming language. The other solutions don't work as well for me. Also I believe the easier way of knowing your IP is to go on the internet. It can be any site, the server can return back your client ip that it got in the request. You can set up your own endpoint for it.

Nick answered 2/12, 2014 at 14:44 Comment(1)
This will fetch the WAN IP address and is in most cases a different address than the LAN IP, which ist what the question is about.Praxis
V
4

Had the same problem, found the solution on this page: http://mrhawy.blogspot.it/2012/05/how-to-get-your-external-ip-address-in.html

    public String getIpAddress() throws MalformedURLException, IOException {
  URL myIP = new URL("http://api.externalip.net/ip/");
  BufferedReader in = new BufferedReader(
                       new InputStreamReader(myIP.openStream())
                      );
  return in.readLine();
  }

had some troubles with this code on the long run, several times in a week the server just won't reply.

new solution:

public static String getIpAddress() 
{ 
        URL myIP;
        try {
            myIP = new URL("http://api.externalip.net/ip/");

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(myIP.openStream())
                    );
            return in.readLine();
        } catch (Exception e) 
        {
            try 
            {
                myIP = new URL("http://myip.dnsomatic.com/");

                BufferedReader in = new BufferedReader(
                        new InputStreamReader(myIP.openStream())
                        );
                return in.readLine();
            } catch (Exception e1) 
            {
                try {
                    myIP = new URL("http://icanhazip.com/");

                    BufferedReader in = new BufferedReader(
                            new InputStreamReader(myIP.openStream())
                            );
                    return in.readLine();
                } catch (Exception e2) {
                    e2.printStackTrace(); 
                }
            }
        }

    return null;
}
Vergievergil answered 2/6, 2013 at 11:44 Comment(0)
I
3

Another option for default network interface, just I was trying 5 min ago and saw your question :)

InetAddress[] localaddr;

try {
    localaddr = InetAddress.getAllByName("host.name");

    for(int i = 0; i < localaddr.length; i++){
        System.out.println("\n" + localaddr[i].getHostAddress());
    }
} catch (UnknownHostException e) {
    e.printStackTrace();
}
Innervate answered 10/11, 2011 at 17:43 Comment(0)
A
3

My Solution which only returns 1 Ip4 address:

try {
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    while (interfaces.hasMoreElements()) {
        NetworkInterface iface = interfaces.nextElement();
        if (iface.isLoopback() || !iface.isUp() || iface.isVirtual() || iface.isPointToPoint())
            continue;

        Enumeration<InetAddress> addresses = iface.getInetAddresses();
        while(addresses.hasMoreElements()) {
            InetAddress addr = addresses.nextElement();

            final String ip = addr.getHostAddress();
            if(Inet4Address.class == addr.getClass()) return ip;
        }
    }
} catch (SocketException e) {
    throw new RuntimeException(e);
}
return null;
Amphitryon answered 23/3, 2016 at 20:23 Comment(0)
M
2
//This program is find your exact LAN(Local Machine on which your are       //runing this program) IP Address 
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class GetMyIPAddress {
public static void main(String gks[]) throws SocketException{
    Enumeration e = NetworkInterface.getNetworkInterfaces();
    int ctr=0;
    while(e.hasMoreElements())
    {
        NetworkInterface n = (NetworkInterface) e.nextElement();
        Enumeration ee = n.getInetAddresses();
        while (ee.hasMoreElements() && ctr<3)
        {       ctr++;
            if(ctr==3)
                break;
                InetAddress i = (InetAddress) ee.nextElement();
                    if(ctr==2)
                         System.out.println(i.getHostAddress());

        }
    }
}

}
Massasauga answered 12/2, 2015 at 12:8 Comment(0)
A
2

Here is my approach to get the IP address.

  1. Get your default gateway address
  2. Get all the address in your PC
  3. Now in your IP(suppose 192.168.100.4) and default gateway IP(suppose 192.168.100.1) have first 9 digit of address must be same, so whichever IP who full this criteria is your IP.

Please see below for full working code.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class MyIpAddress {

    public static void main(String[] args) {
        // doPortForwarding();

        MyIpAddress myIpAddress = new MyIpAddress();

        // get default address
        String yourIp = myIpAddress.getYourIp(myIpAddress
                .getDefaultGateWayAddress());
        System.out.println(yourIp);

        // get

    } // amin

    // return ip address for which u need to do port forwarding
    private String getYourIp(String defaultAddress) {

        String temp = defaultAddress.substring(0, 11);
        String ipToForward = "";

        TreeSet<String> ipAddrs = getIpAddressList();
        for (Iterator<String> iterator = ipAddrs.iterator(); iterator.hasNext();) {

            String tempIp = iterator.next();
            if (tempIp.contains(temp)) {
                ipToForward = tempIp;
                break;
            }
        }

        return ipToForward;

    }// ipForPortForwarding

    // get the ipaddress list
    private TreeSet<String> getIpAddressList() {
        TreeSet<String> ipAddrs = new TreeSet<String>();

        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface
                    .getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface iface = interfaces.nextElement();
                // filters out 127.0.0.1 and inactive interfaces
                if (iface.isLoopback() || !iface.isUp())
                    continue;

                Enumeration<InetAddress> addresses = iface.getInetAddresses();
                while (addresses.hasMoreElements()) {

                    InetAddress addr = addresses.nextElement();

                    ipAddrs.add(addr.getHostAddress());

                }// 2 nd while
            }// 1 st while
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return ipAddrs;

    }// getIpAddressList

    // get default gateway address in java

    private String getDefaultGateWayAddress() {
        String defaultAddress = "";
        try {
            Process result = Runtime.getRuntime().exec("netstat -rn");

            BufferedReader output = new BufferedReader(new InputStreamReader(
                    result.getInputStream()));

            String line = output.readLine();
            while (line != null) {
                if (line.contains("0.0.0.0")) {

                    StringTokenizer stringTokenizer = new StringTokenizer(line);
                    stringTokenizer.nextElement();// first string is 0.0.0.0
                    stringTokenizer.nextElement();// second string is 0.0.0.0
                    defaultAddress = (String) stringTokenizer.nextElement(); // this is our default address
                    break;
                }

                line = output.readLine();

            }// while
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return defaultAddress;

    }// getDefaultAddress
}
Accouterment answered 17/4, 2016 at 18:26 Comment(0)
D
1

You need to get the jar of jsoup here add the jar of jsoup in your java project and interpret this lines of code and you will get your ip adress,

Document doc = Jsoup.connect("https://whatismyipaddress.com/").timeout(10000).get() ;
Elements el = doc.select("div#section_left") ;
Element e = el.select("a").get(
System.out.println(e.text());
Dude answered 16/6, 2018 at 13:28 Comment(0)
C
0

You can get your IP address by writing a simple code. `

import java.net.InetAddress;

public class Main {
    public static void main(String[] args) throws Exception
    {
        System.out.println(InetAddress.getLocalHost());
    }
}
Cf answered 10/1, 2020 at 11:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.