如何以编程方式获取公共IP地址? [英] How to programmatically get a public IP address?

查看:78
本文介绍了如何以编程方式获取公共IP地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有找到正确的解决方案.下面的代码为我提供了本地IP地址(如果我连接到Wifi,它会提供IP地址,例如192.168.0.x),但是我想要公共IP地址(就像我在Google中搜索什么是我的IP"一样)

I didn't find the right solution. The below code gives me local IP address (if I connected to Wifi, it gives IP address like 192.168.0.x), but I want public IP address (same as if I search in google " what is my 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;
}

OR

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

任何人都可以帮忙吗?谢谢!

Can anyone help? Thanks!

推荐答案

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

Step #1: Create a Web service that returns the requester's IP address

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

Step #2: Call that Web service from your app.

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

A device does not know its public IP address (unless that device was seriously misconfigured).

这篇关于如何以编程方式获取公共IP地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆