问:-现在我在使用编程获取 android 设备的 IP 地址时遇到问题。任何人都可以给ma一个解决这个问题的代码。我已经阅读了很多关于它的主题,但没有从中得到可靠的答案。请给我任何关于它的建议。提前致谢。
问问题
7447 次
2 回答
4
问题是您无法知道您当前使用的网络设备是否真的有公共 IP。但是,您可以检查是否是这种情况,但您需要联系外部服务器。
在这种情况下,我们可以使用www.whatismyip.com来检查(几乎是从另一个 SO 问题中复制的):
public static InetAddress getExternalIp() throws IOException {
URL url = new URL("http://automation.whatismyip.com/n09230945.asp");
URLConnection connection = url.openConnection();
connection.addRequestProperty("Protocol", "Http/1.1");
connection.addRequestProperty("Connection", "keep-alive");
connection.addRequestProperty("Keep-Alive", "1000");
connection.addRequestProperty("User-Agent", "Web-Agent");
Scanner s = new Scanner(connection.getInputStream());
try {
return InetAddress.getByName(s.nextLine());
} finally {
s.close();
}
}
要检查此 ip 是否绑定到您的网络接口之一:
public static boolean isIpBoundToNetworkInterface(InetAddress ip) {
try {
Enumeration<NetworkInterface> nets =
NetworkInterface.getNetworkInterfaces();
while (nets.hasMoreElements()) {
NetworkInterface intf = nets.nextElement();
Enumeration<InetAddress> ips = intf.getInetAddresses();
while (ips.hasMoreElements())
if (ip.equals(ips.nextElement()))
return true;
}
} catch (SocketException e) {
// ignore
}
return false;
}
测试代码:
public static void main(String[] args) throws IOException {
InetAddress ip = getExternalIp();
if (!isIpBoundToNetworkInterface(ip))
throw new IOException("Could not find external ip");
System.out.println(ip);
}
于 2012-06-14T10:47:38.843 回答
2
对于无线网络:
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
或者更复杂的解决方案:
public 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()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e(LOG_TAG, ex.toString());
}
return null;
}
于 2012-06-14T10:10:38.690 回答