6

我拿起了我的一些旧代码进行重建,而曾经在我的平板电脑和手机上工作的方法之一不再有效。我正在尝试使用我在此处获取的例程来获取我的 IP 地址。

当程序执行第 4 行时(以“for (Enumeration...”开头),它立即跳转到异常捕获部分。异常没有消息,对于字符串 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;
}
4

1 回答 1

21

只是为了澄清一个完整的答案。

NetworkInterface.getNetworkInterfaces()

SocketException如果应用程序缺少此权限,则抛出AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />

在我的测试中(在 Android 4.4.2 上)android.permission.ACCESS_NETWORK_STATE可以跳过。

于 2014-05-21T13:58:10.140 回答