Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NetworkInterface.getNetworkInterfaces() throws exception with null message string

I picked up some old code of mine to rebuild and one of the methods that used to work on my tablet and phone no longer works. I'm trying to use a routine I picked up here to get my IP address.

When the program executes line 4 (starting with "for (Enumeration..." it immediately jumps to the exception catch section. The exception has no message and for the string the ex.getMessage() returns null. The exception number is 830034796568 (decimal).

Here's the code. As mentioned this worked fine a year ago.

Thanks for any help!

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;
}
like image 764
moticon Avatar asked Apr 21 '13 02:04

moticon


1 Answers

Just to clarify with a full answer.

NetworkInterface.getNetworkInterfaces()

throws a SocketException if the application is missing this permission in AndroidManifest.xml

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

In my tests (on Android 4.4.2) android.permission.ACCESS_NETWORK_STATE can be skipped.

like image 91
MaxChinni Avatar answered Oct 19 '22 18:10

MaxChinni