我拿起了我的一些旧代码进行重建,而曾经在我的平板电脑和手机上工作的方法之一不再有效。我正在尝试使用我在此处获取的例程来获取我的 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;
}