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!
You can pretty much bet any answer is going to link OSI Model. . . – surfasb – 2011-07-28T03:25:09.507