问:现在我在使用编程获取Android设备的IP地址时遇到问题。任何人都可以给出解决该问题的代码。我已经阅读了很多关于它的帖子,但没有从中获得可靠的答案。请给我任何建议,赞赏它。 提前致谢。
答案 0 :(得分:5)
问题是您无法知道当前使用的网络设备是否确实具有公共IP。但是,您可以检查是否是这种情况,但您需要联系外部服务器。
在这种情况下,我们可以使用www.whatismyip.com来检查(almost copied from another SO question):
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);
}
答案 1 :(得分:2)
对于wifi:
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;
}