Android NetworkInterface.getNetworkInterfaces()引发带有空消息字符串的异常
我拿起我的一些旧代码进行重建,而在我的平板电脑和手机上使用的一种方法已经不起作用了。我正在尝试使用我在这里学习的例程来获取我的IP地址 当程序执行第4行(以“for(枚举…”开头)时,它立即跳转到异常捕获部分。异常没有消息,对于字符串,ex.getMessage()返回null。异常号为830034796568(十进制) 这是代码。正如一年前所提到的,它工作得很好 谢谢你的帮助Android NetworkInterface.getNetworkInterfaces()引发带有空消息字符串的异常,android,ip-address,Android,Ip Address,我拿起我的一些旧代码进行重建,而在我的平板电脑和手机上使用的一种方法已经不起作用了。我正在尝试使用我在这里学习的例程来获取我的IP地址 当程序执行第4行(以“for(枚举…”开头)时,它立即跳转到异常捕获部分。异常没有消息,对于字符串,ex.getMessage()返回null。异常号为830034796568(十进制) 这是代码。正如一年前所提到的,它工作得很好 谢谢你的帮助 public String getLocalIpAddress() { String address= nul
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;
}
公共字符串getLocalIpAddress(){
字符串地址=空;
试试{
对于(枚举en=NetworkInterface.getNetworkInterfaces();en.hasMoreElements();){
NetworkInterface intf=en.nextElement();
对于(枚举Enumeration EnumipAddress=intf.getInetAddresses();EnumipAddress.hasMoreElements();){
InetAddress InetAddress=enumIpAddr.nextElement();
地址=新字符串(inetAddress.getHostAddress().toString());
如果(!inetAddress.isLoopbackAddress()&&address.length()<18){
返回inetAddress.getHostAddress().toString();
}
}
}
}捕获(SocketException例外){
字符串msg=ex.getMessage();
//无所事事
}
返回null;
}
只是想用完整的答案澄清一下
NetworkInterface.getNetworkInterfaces()
如果应用程序在AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
在我的测试中(在Android 4.4.2上)
Android.permission.ACCESS\u NETWORK\u STATE
可以被跳过。你能将SocketException包装在RuntimeException中并重新播放它,这样我们就可以看到完整的堆栈跟踪吗?我把它改为“throw RuntimeException(ex)”;Eclipse调试器显示的stacktrace为空。我对此有点陌生,启动时有些生疏。我能做些什么来显示信息以帮助其他人帮助我吗?我允许android.permission.INTERNET的权限,但错过了android.permission.ACCESS\u NETWORK\u状态。但我可以在没有INTERNET的情况下使用接口,有吗未经接口许可获取网络接口的方法