How to make two android devices to communicate through TCP How to make two android devices to communicate through TCP android android

How to make two android devices to communicate through TCP


Is this a problem for creating a TCP socket?

Answer is no, it does not make it impossible (unless NAT's have an unpredictable way of mapping IP addresses). However, it is not simple to accomplish.

The short answer is you'll always need a server-like peer with a public IP address to facilitate initial communication between peers located behind NATs. The peers connect to it. A tells server it wants to TCP connect with B. Server notifies B. NAT behavior analysis is performed and if possible, A and B attempt to open TCP communications with each other by predicting the next mapping of the other NAT. If all goes fine (and usually it does) A touches base with B or vice-versa. They close the other connection attempts and communicate with the operational TCP connection. This technique is called STUN for TCP.

Now, there are more complicated reason why things can go wrong. If you want to know more, I have written a book called Practical JXTA II which available for reading online at Scribd. There is a chapter dedicated to NAT traversal.

Hope this helps.


One device behind a NAT is not a problem. The requirement is: the server must be reachable by the client.

I'm using Apache Mina to handle TCP connections. It have really made my life easier. It can be used on both client and server. Give it a try...


Well to make a TCP socket one device must be listening and the other connecting. However in a real world scenario what you describe is sort of hard.Like if you are going to communicate over a cell network between two phones, I wouldn't be surprised if the network did not allow inbound connections to a phone like that and just sandboxed each phone's IP. So while two phones might be on the same subnet IP range, they might not be on the same physical network which just makes the whole routing problem almost impossible.

If you are in control of the network and are using Wifi and natting the IPs yourself with both devices within your network, you should be able to do this just like any other client server TCP socket.