Search code examples
c++windowstcpoperating-systemnetwork-programming

Why we should specify a Port for our network connection?


I begin network programming with C++ in Windows OS. I know what is a Network protocol stack (like Educational Model of OSI and Operational Model of TCP/IP). Also, I know how a packet routed and switched in a network medium and many more other concepts about network programming and communication itself.

However, I know now when a process in Machine A wants to send a message to another process in machine B, the message must go through TCP/IP stack layers until it could be ready to put on physical media to reach the destination process in Machine B.

Packet should have the destination IP address of Machine B and also a Port Number. But I could not figure out the answer to the following questions:

  1. Why we should specify a Port and how these 6000+ ports in operating systems (Windows) distinguished from each other?

  2. How TCP/IP network protocol stack implemented in Windows OS? It is a driver or something else.

  3. In Windows operating systems, every process has a TCP/IP protocol for itself or windows process uses the same TCP/IP protocol stack for them?

I know, these kinda questions are not too good for StackOverflow fans, but unfortunately, I couldn't find out the answer to these questions in the books or even via googling.


Solution

  • The port number is used to distinguish different applications running on the same machine from each other. Usually all (at least most) programs on the same machine will be communicating via the same IP address. The kernel needs to know what messages to dispatch to what program, the port number solves this problem. Each program will be communicating on a unique port, so when a message arrives for port x, the kernel knows what program to send the message to. Without the port number it would have to send the message to all programs and they would have to figure out if any given message was meant for them.

    As for what books to read; I'd recommend "TCP/IP Illustrated, Volume 1 through 3" and UNIX Network Programming.