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

vid*_*dha 2 ip networking android

我找不到合适的解决方案.下面的代码给了我本地IP地址(如果我连接到Wifi,它提供的IP地址如192.168.0.x),但我想要公共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;
}
Run Code Online (Sandbox Code Playgroud)

要么

WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
    String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙吗?谢谢!

Com*_*are 10

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

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

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


Ano*_*p M 9

您可以使用WS https://api.whatismyip.com/ip.php来自whatismyip.com:这将在简单的文本输出只有您的IP地址.(无需输入,输出可选)

您必须是金级会员才能访问API

更新的答案

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

请阅读此处的文档

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

您应该使用ipify,因为:

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

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

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


Ant*_*raz 8

我找到了这个简单的解决方案:

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();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请记住,这必须在单独的线程上运行。