我拿起我的一些旧代码来重建,其中一个曾经在我的平板电脑和手机上工作的方法不再有效。我正在尝试使用我在这里获得的一个例程来获取我的IP地址。
当程序执行第4行时(以"for (枚举...“它会立即跳转到异常捕获部分。异常没有消息,对于字符串,ex.getMessage()返回null。异常编号为830034796568 (十进制)。
这是代码。正如前面提到的,这在一年前运行得很好。
谢谢你的帮助!
public String getLocalIpAddress() {
String address= null;
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();
address = new String(inetAddress.getHostAddress().toString());
if (!inetAddress.isLoopbackAddress() && address.length() < 18) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
String msg = ex.getMessage();
//do nothing
}
return null;
}
发布于 2014-05-21 21:58:10
只是想用一个完整的答案来澄清一下。
NetworkInterface.getNetworkInterfaces()
如果应用程序在AndroidManifest.xml
中缺少此权限,则引发SocketException
<uses-permission android:name="android.permission.INTERNET" />
在我的测试中(在Android 4.4.2上),可以跳过android.permission.ACCESS_NETWORK_STATE
。
https://stackoverflow.com/questions/16127263
复制相似问题