简体   繁体   English

Java获取我的IP地址

[英]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我试图在 Java 中获取我的 Internet IP 地址,但是当我的 IP 地址是 192.168.0.xxx 时,我一直在获取我的本地地址(即:127.0.0.1)

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.这似乎是获取 IP 地址的标准,但这不是我想要的。 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?任何人都可以请告诉我如何获得正确的IP地址吗?


I'm running on a device that is connected to WiFi, and I'm not using any cable.我在连接到 WiFi 的设备上运行,我没有使用任何电缆。 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.我正在使用 ifconfig inet addr 提供的 IP 连接到服务器,并且我希望获得设备的 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.我可以检查服务器端套接字的 IP,但认为如果设备(客户端)告诉服务器他希望其他设备连接哪个 IP,那会更好。

    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". NetworkInterface类包含所有相关方法,但请注意,没有“我的 IP”这样的东西。 A machine can have multiple interfaces and each interface can have multiple IPs.一台机器可以有多个接口,每个接口可以有多个IP。

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.您可以使用此类将它们全部列出,但是您从列表中选择哪个接口和 IP 取决于您确切需要使用此 IP 的目的。

( InetAddress.getLocalHost() doesn't consult your interfaces, it simply returns constant 127.0.0.1 (for IPv4)) InetAddress.getLocalHost()不咨询您的接口,它只是返回常量 127.0.0.1 (对于 IPv4))

Let's ask AWS让我们问问 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.在您投反对票之前,我很清楚这不是 Java 解决方案。 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.此外,我相信了解您的 IP 的更简单方法是上网。 It can be any site, the server can return back your client ip that it got in the request.它可以是任何站点,服务器可以返回它在请求中获得的客户端 IP。 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有同样的问题,在这个页面上找到了解决方案: 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 :)默认网络接口的另一个选项,只是我 5 分钟前尝试并看到您的问题:)

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:我的解决方案只返回 1 个 Ip4 地址:

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.这是我获取IP地址的方法。

  1. Get your default gateway address获取您的默认网关地址
  2. Get all the address in your PC获取 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.现在在您的 IP(假设 192.168.100.4)和默认网关 IP(假设 192.168.100.1)中的前 9 位地址必须相同,因此满足此条件的 IP 就是您的 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,您需要在此处获取jsoup jar 在您的java 项目中添加jsoup jar 并解释这行代码,您将获得您的ip 地址,

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.您可以通过编写简单的代码来获取您的 IP 地址。 ` `

import java.net.InetAddress;

public class Main {
    public static void main(String[] args) throws Exception
    {
        System.out.println(InetAddress.getLocalHost());
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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