SocketExceptions with Android

I’ve run into two SocketExceptions with Android today and wanted to post the solutions here to save time for others. First is the following permission error the app was trying to create a socket connection:

08-26 06:42:15.784: WARN/System.err(447): java.net.SocketException: Permission denied

Turns out that, in Android, applications don’t have access to the internet by default, you need to enable it as explained by some good folks here. The solution is to add this line in the root of the AndroidManifest.xml file of your application:


The second error was more tricky. It happened during socket creation again and the stacktrace was as follows:

08-26 08:00:03.838: WARN/System.err(421): java.net.SocketException: Bad address family

...
26 08:00:03.888: WARN/System.err(421):     at java.nio.channels.Selector.open(Selector.java:48)

This is due to Android emulator not supporting IPv6. I’m not sure if it’s just the Android emulator or if it’s a general bug with Android 2.2 (that apparently got fixed) but the details are provided by folks here and the temporary solution is to disable IPv6 before calling selector with this call:

System.setProperty("java.net.preferIPv6Addresses", "false");

Hope, this saves some time for someone else!

Advertisements