Home » Android » sockets – Can't use ServerSocket on Android

sockets – Can't use ServerSocket on Android

Posted by: admin May 14, 2020 Leave a comment


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,, 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?

The code is simple as this:

ServerSocket server = new ServerSocket();
server.bind(new InetSocketAddress(4040));

Socket client = null;
while((client = server.accept()) == null);
// Connected
enter code here
enter code here
How to&Answers:

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() )


I struggled with this too and was only able to connect to my Android server by using:

ServerSocket myServerSocket = new ServerSocket();
String hostname = getLocalIpAddress();
myServerSocket.bind(new InetSocketAddress(hostname, myPort));

Where hostname was the local IP, which I got using the getLocalIpAddress() function from this page:



I was able to get this working by using

 ServerSocket server = new ServerSocket( myTcpPort, 0, addr );

where addr = InetAddress of your phone. Otherwise, it only seems to bind to localhost ( Also, I’m using port 8080.