Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple TCP communication with a computer behind a router

Tags:

tcp

sockets

nat

I'm writing a C# remote control for my media player. It runs on my Android phone.

I have a client app listening for TCP connections on my computer which, one a connection has been established, processes commands (Volume up, volume down, ...). I've tested that part using telnet 127.0.0.1 on my computer, and it works great.

Things are trickier when it comes to connecting from my phone, since it's not on the same network (I don't have Wi-Fi, only wired connections), so I'm not sure how to proceed. Basically I want to connect to a computer that's behind a router.

Should I rather host the TCP server on my phone, and have the PC connect to it? Take IRC as an example: although I'm behind a router, I can connect to servers outside, without port forwarding. Or if hosting the server on my computer is fine, how do I connect to it?

I don't understand everything to this yet, so feel free to correct me if I got something wrong.

like image 256
Clément Avatar asked Mar 04 '12 22:03

Clément


2 Answers

It would be more logical to keep the PC hosting the server, and configure your router to forward connections to your PC. You have two options:

  • Establish a DMZ: all incoming connections on the router will be forwarded to one PC only. This is easiest when you only have 1 PC on the network that needs to accept connections.
  • Configure port forwarding: you can instruct the router to forward connections incoming on port X to the IP Y on port Z. This way, multiple PC's can listing for connections (using different ports on the router). It is also a bit more secure.

How to set these up depends on your router, but most routers just accept connections on their port 80 and offer an easy web-interface. If you give your router brand, we can link you to the manual.

like image 158
Konerak Avatar answered Nov 07 '22 13:11

Konerak


Things are trickier when it comes to connecting from my phone, since it's not on the same network (I don't have Wi-Fi, only wired connections), so I'm not sure how to proceed. Basically I want to connect to a computer that's behind a router.

What you want to achieve is possible, but you need to learn about NAT traversal and hole punching.

Most often, devices behind a NAT/Router have a private IP address only valid on the LAN. Remote devices can't guess it. This private address is translated into a public IP address by the NAT when the device wants to communicate with the WAN.

The easy solution is you can give a public IP address to the device behind the NAT. In this case, remote devices on the WAN will easily be able to reach it, because its address is public.

like image 26
Jérôme Verstrynge Avatar answered Nov 07 '22 14:11

Jérôme Verstrynge