Q & A on Ports and Sockets

Q: 1. can you clarify the difference between a port and a socket?

A: A socket is an operating system abstraction similar to a file descriptor; it is part of the Application Program Interface (API). A program creates a socket, specifies that it will be used with TCP/IP, and then fills in details such as whether the socket will be used by a client or a server.

A port is a transport-layer abstraction that is part of the TCP/IP suite. Each port is a 16-bit integer; the space of ports for TCP and UDP are separate. Ports used by servers are given reserved values (e.g., a Web server uses port number 80).

Note that after creating a socket, a program specifies a port to be used with that socket.

Q: 2. also when can two processes end up sharing the same port (except the case when forking is done after binding to a port then parent-child share it).

Yes, two processes can share the same port. Sharing is most common in TCP because TCP identifies a connection by 4 items:

  • Client IP address
  • Client port number
  • Server IP address
  • Server port number

Thus, two processes can provide Web service on port 80 concurrently as long as the two TCP connections go to different clients.