Can't use ServerSocket on Android

shuwo picture shuwo · Aug 28, 2010 · Viewed 11.1k times · Source

I'm trying to listen on a port using ServerSocket on an Android device. I want to be able to connect to this port over WiFi using a computer on the same network.

I get no exception when binding it to a port, however when I check netstat it says:

Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 (null):4040             (null):*                LISTEN

I've tried countless ways of binding it to localhost, 0.0.0.0, the WiFi LAN IP address of the device with SocketInetAddress and InetAddress.getByName. Nothing seems to work.

When I try to connect to the port from a computer in the same WiFi (I've tried both netcat and Java's Socket.connect()), all I can see in Wireshark is an ARP request:

Who has [phone's LAN address]? Tell [computer LAN address].

This request repeat itself until timed out.

I've tried the reverse way, by setting the ServerSocket on the computer and connecting to that port from the phone, that works very well.

My testing phone is an Samsung Spica i5700 with a custom ROM.

Any ideas?

Edit: The code is simple as this:

ServerSocket server = new ServerSocket();
server.setReuseAddr(true);
server.setTimeout(0);
server.bind(new InetSocketAddress(4040));

Socket client = null;
while((client = server.accept()) == null);
// Connected
enter code here
enter code here

Answer

Alex Florescu picture Alex Florescu · Nov 3, 2010

Instead of using server.bind, try initializing the server socket like this: server = new ServerSocket(4040);

Also, server.accept() will actually block until a connection is made, so you don't need that while loop (see: http://download.oracle.com/javase/1.5.0/docs/api/java/net/ServerSocket.html#accept() )