Java getting my IP address

走远了吗. 提交于 2019-11-26 20:24:34

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

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

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

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

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());
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!