Search code examples
tcp

How does a system's TCP/IP stack differentiate between multiple programs connecting to the same address and port?


Suppose two web browsers are running on the same computer and are accessing the same website (in other words, accessing the same IP address on the same port).

How does the operating system recognize which packets are from/for which program?

Does each program have a unique id field in the TCP header? If so, what is the field called?


Solution

  • The two programs are not actually accessing the "same port." For purposes of TCP, a connection is defined by the tuple (src_ip,src_port,dst_ip,dst_port).

    The source port is usually ephemeral, which means it is randomly assigned by the OS. In other words:

    Program A will have:

    (my_ip, 10000, your_ip, 80)

    Program B will have:

    (my_ip, 10001, your_ip, 80)

    Thus, the OS can see those are different "connections" and can push the packets to the correct socket objects.