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)
有人可以帮忙吗?谢谢!
您可以使用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,因为:
....................
....................
我找到了这个简单的解决方案:
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)
请记住,这必须在单独的线程上运行。