我需要列出任何特定Android设备的所有可用IP地址。
我找到了一些示例代码,但这只会导致返回一个IP地址,这恰好是一个IPv6地址。我需要为任何特定设备获取所有可用的IP。我在这个应用程序的iOS版本上做同样的事情,它返回3个IPv6地址,一个192.
地址和一个10.
地址。我试图在Android上复制相同的内容。我将所有值传递给数组并将其显示在列表中。
我的代码是:
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()) {
IPAddresses.setText(inetAddress.getHostAddress().toString());
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
String LOG_TAG = null;
Log.e(LOG_TAG, ex.toString());
}
return null;
}
答案 0 :(得分:5)
在我看来,你的代码只是返回第一场比赛 - 这不是问题吗?我本来希望你建立地址列表,并返回而不是只有一个字符串。像这样:
public String[] getLocalIpAddress()
{
ArrayList<String> addresses = new ArrayList<String>();
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()) {
IPAddresses.setText(inetAddress.getHostAddress().toString());
addresses.add(inetAddress.getHostAddress().toString());
}
}
}
} catch (SocketException ex) {
String LOG_TAG = null;
Log.e(LOG_TAG, ex.toString());
}
return addresses.toArray(new String[0]);
}
我不确定IPAddresses.setText
调用是做什么的,所以我把它留在了,但我希望还需要以某种方式调整以处理你可能有多个地址的事实匹配。