如何以编程方式获取公共IP地址?

7

我没有找到正确的解决方案。下面的代码给我本地IP地址(如果我连接到Wifi,它会给出类似于192.168.0.x的IP地址),但是我想要公共IP地址(就像在谷歌中搜索“我的IP是什么”一样)

public static String getLocalIpAddress() {
try {
    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
        NetworkInterface intf = en.nextElement();
        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
            InetAddress inetAddress = enumIpAddr.nextElement();
            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                return inetAddress.getHostAddress();
            }
        }
    }
} catch (SocketException ex) {
    ex.printStackTrace();
}
return null;
}

或者

WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
    String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());

有人能帮忙吗?谢谢!


1
可能是如何从代码中获取设备的IP地址?的重复问题。 - Firoz Memon
5个回答

20

步骤1:创建一个返回请求者IP地址的Web服务。

步骤2:从您的应用程序中调用该Web服务。

设备不知道其公共IP地址(除非该设备严重配置错误)。


其他的答案让我感到很烦。非常感谢! - Soon Santos

12

您可以使用由whatismyip.com提供的WShttps://api.whatismyip.com/ip.php:这将仅以简单文本输出您的IP地址。(无需输入,输出可选)

要访问API,您必须是Gold级会员。

更新回答

您可以使用ipify.org的Web服务。

在此文档中阅读说明书。

使用https://api.ipify.org/?format=json WS获取设备公共IP地址。 这将以JSON格式输出您的IP地址。

您应该使用ipify,因为:

  • 您可以无限制地使用它(即使您每分钟进行数百万次请求)。
  • 它始终在线并可用,其基础架构由Heroku提供支持,这意味着无论运行API的服务器是否死机,或者是否有一场摧毁了东海岸一半的巨大龙卷风,ipify仍然会运行!
  • 它与IPv4和IPv6地址完美配合,因此无论您使用何种技术,都不会出现问题。

....................

....................


您必须成为金牌会员才能访问API。您是WhatIsMyIP.com的金牌会员吗? - Anoop M Maddasseri
使用需要成为会员的服务器并没有太多意义。而且你为什么不立即告诉我呢? - greenapps
据他们称,文档仍然有效,没有发现任何弃用说明。 - Anoop M Maddasseri
1
他们已经在那里数十年了,就像你提到的那一个,没有任何区别。 - greenapps
1
请确保您的隐私政策指明您正在向他人的Web服务发出此类请求,而不是您自己的Web服务。 - CommonsWare
显示剩余2条评论

7
我找到了这个简单的解决方案:
public String getExternalIpAddress() throws Exception {
    URL whatismyip = new URL("http://checkip.amazonaws.com");
    BufferedReader in = null;
    try {
        in = new BufferedReader(new InputStreamReader(
                whatismyip.openStream()));
        String ip = in.readLine();
        return ip;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

记住这一定要在单独的线程中运行。


在线提供了一个非常棒的解决方案 :) - Zia
这个 API 的使用有没有最大限制? - hetsgandhi

2
你可以通过简单的线程来实现这个功能。你需要在Activity.class文件中创建一个函数,并请求一个返回公共IP地址的文本形式的URL: "https://api.ipify.org/点击打开。"
将这个函数调用添加到你的onCreate()函数中即可。
    getPublicIP();
在您的MainActivity.class中添加此功能。

    private void getPublicIP() {

        new Thread(new Runnable(){
            public void run(){
                //TextView t; //to show the result, please declare and find it inside onCreate()

                try {
                    // Create a URL for the desired page
                    URL url = new URL("https://api.ipify.org/"); //My text file location
                    //First open the connection
                    HttpURLConnection conn=(HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(60000); // timing out in a minute

                    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

                    //t=(TextView)findViewById(R.id.TextView1); // ideally do this in onCreate()
                    String str;
                    while ((str = in.readLine()) != null) {
                        urls.add(str);
                    }
                    in.close();
                } catch (Exception e) {
                    Log.d("MyTag",e.toString());
                }

                //since we are in background thread, to post results we have to go back to ui thread. do the following for that

                PermissionsActivity.this.runOnUiThread(new Runnable(){
                    public void run(){
                        try {
                            Toast.makeText(PermissionsActivity.this, "Public IP:"+urls.get(0), Toast.LENGTH_SHORT).show();
                        }
                        catch (Exception e){
                            Toast.makeText(PermissionsActivity.this, "TurnOn wiffi to get public ip", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

            }
        }).start();

    }


-2

1
请确保您的隐私政策指出,您正在向他人的 Web 服务发出这些请求,而不是您自己的服务。 - CommonsWare

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