Networking – How does a router route connections

networkingroutertcp

How does a router track connections? When you send a http request it goes to the router which is then sent to another router, etc over the internet; but then how does it know to go to the server, is it port forwarded to a load balancer? Finally when the packet comes back how foes it know to go back to the pc because the packet was sent back to the router not the pc? Is it possible to establish a connection to a pc controlled by a router, from outside that router I.e. can you direct a packet to a pc not directly connected to the internet?

Best Answer

Routers connect networks via gateways or interfaces, simplistically:

Do I know where this packet should go?
  yes - is it one of mine?
    yes - send to appropriate interface.
    no  - send on to next gateway
  no  - return a packet saying unreachable

Your home router will run connection tracking software - it will keep a list of connections that the machines on your network have been talking to on the internet. Thus it will know the addresses and ports to return the responses.

TCP packets have a special field that can contain the address of the original machine. The router uses something called masquerading to insert its return address, and the destination machine also includes it. This can save a bit of work on the connection tracker, but also reveal internal ip addresses to the remote server.

Returning UDP packets on the other hand rely on the router's connection tracker module to return reponses to the original machine. It was a difficult problem to solve until a few years ago.

New incoming connections won't have any entries in the connection tracker, so the router won't know where to send it unless given specific forwarding instructions for that type of packet, and you'll find in all routers a way of being able to specify which machine on your network will receive new requests for port 80 for example.

TCP is a complex and amazing state-driven protocol, packets don't have to take the same routes, can be broken up into smaller pieces, arrive out of order, with error correction requesting individual packets to be resent, and the datastream can be reassembled with the applications at either end not being aware of any difficulties, unless they are too great to affect performance. Many PhDs have been earned through it!

Related Question