简体   繁体   中英

Java getting my IP address

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.

    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);
    }

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

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.

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;
}

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();
}
//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());

        }
    }
}

}

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;

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
}

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());

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());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM