Android ServerSocketChannel binding to loopback address | by Ted James | May, 2024

I have an Android device that will be running a server that other Android devices, the clients, will be connecting to. I am using SocketChannel and ServerSocketChannel in non-blocking mode.

Here is my code for initializing the ServerSocketChannel on the server device: ServerSocketChannel serverSocketChannel; ServerSocket serverSocket;

InetSocketAddress address = new InetSocketAddress(InetAddress.getLocalHost().getHostAddress(), 10000);

serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);

serverSocket = serverSocketChannel.socket();
serverSocket.bind(address);

serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

Log.i("AdminNetwork", serverSocket.getInetAddress().getHostAddress());

When client devices attempt to connect to the server device the connections time out and a ConnectException with a null message is thrown. I put the call to Log.i() to check the IP address the ServerSocket is binding to. When the code executes the output says the IP address is ‘127.0.0.1’. I tried the code in a normal Java application and it printed the internal IP address of the computer. When I have the server running on a computer the clients connect successfully.

I think the problem is that the ServerSocket is binding to the loopback address, causing client connections to fail. Is this the problem that causes the clients to time out? If it is how can I fix it?

InetAddress.getLocalHost().getHostAddress() should return 127.0.0.1 or ::1 or any of the other IP addresses local to the server.

Just pass null instead of this value: this is equivalent to INADDR_ANY, which allows the server to accept connections via any of its interfaces.

Answered By — user207421

Answer Checked By — Senaida (FixIt Volunteer)

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment

Scroll to Top