Java获取我的IP地址

38

我正在尝试在Java中获取我的公网IP地址,但是我一直得到的是我的本地地址(例如:127.0.0.1),而我的IP地址是192.168.0.xxx。

我正在使用以下代码:

InetAddress.getLocalHost().getHostAddress();

这似乎是获取IP地址的标准方法,但这不是我要找的。每个教程都说要使用这行代码,所以我有点困惑。

请问有人能告诉我如何获取我的正确IP地址吗?


我正在运行连接到WiFi的设备上,没有使用任何电缆。我正在使用ifconfig inet addr给出的IP地址连接到服务器,并且希望获取设备的inet addr。我可以在服务器端检查套接字的IP地址,但认为如果设备(客户端)告诉服务器它期望其他设备连接的IP地址会更好。


1
你是否可能是通过本地主机连接到服务器的?这段代码是在服务器上运行还是在桌面应用程序上或其他位置运行? - Mike Christensen
3
“IP地址”是什么?我的电脑目前至少有五个。 - themel
1
从文档中可以看到:如果存在安全管理器,则使用本地主机名和-1作为参数调用其checkConnect方法以查看是否允许该操作。如果不允许该操作,则返回表示环回地址的InetAddress。 - Mike Christensen
1
https://dev59.com/fXRB5IYBdhLWcg3w1Kr0 - vanje
也许我应该让服务器调用getRemoteSocketAddress().toString()来获取客户端的套接字,而不是尝试让客户端查找自己的IP。 - Jary
显示剩余2条评论
10个回答

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

24

NetworkInterface类包含了所有相关的方法,但请注意,“我的IP地址”这种说法是不存在的。一台机器可以拥有多个网络接口,每个接口可以有多个IP地址。

你可以使用这个类列出它们,但是选择哪个接口和IP地址取决于你需要使用这个IP地址的具体用途。

(InetAddress.getLocalHost()不会查询你的接口,它只会返回常量127.0.0.1(对于IPv4))


16

让我们问问AWS

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

编辑

在你投票之前,我很清楚这不是一个Java解决方案。这是适用于任何编程语言的通用解决方案。其他解决方案对我来说都不太有效。此外,我认为知道你的IP地址的更简单方法是上网。它可以是任何站点,服务器可以返回它在请求中获取的客户端IP。您可以为此设置自己的端点。


4
这将获取WAN IP地址,在大多数情况下,这个地址与LAN IP不同,这也是问题所在。 - l4mpi

4

我曾经遇到过同样的问题,后来在这个页面上找到了解决方案: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();
  }

在长期使用中,这段代码遇到了一些问题,一周之内会有几次服务器无法响应。

新的解决方案:

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

3

还有一种默认网络接口的选项,就在我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();
}

3

我的解决方案只返回一个IPv4地址:

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;

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

        }
    }
}

}

2

以下是获取IP地址的方法:

  1. 获取默认网关地址
  2. 获取计算机中的所有地址
  3. 现在,在您的IP地址(假设为192.168.100.4)和默认网关IP地址(假设为192.168.100.1)中,前9位数字必须相同,因此符合此条件的任何IP地址都是您的IP地址。

请参见下面的完整工作代码。

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
}

1

您需要获取jsoup的jar包这里 将jsoup的jar包添加到您的Java项目中,并解释以下代码行,您将获得您的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());

0

你可以编写简单的代码来获取你的IP地址。

import java.net.InetAddress;

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接