How do ports and sockets allow multiple applications to use the same IP address?
Interview preparation resource from Gate Smashers.
An IP address identifies the destination host or network interface, but it does not identify the receiving application. Transport-layer ports let the operating system deliver incoming TCP or UDP data to the appropriate application endpoint on that IP address. A socket is the operating-system-managed communication endpoint an application uses to send or receive that data. Thus, multiple applications can share one IP address by using different protocol-and-port combinations, and multiple connections to one service can coexist because their connection identifiers differ.
IP address, port, and protocol
The IP address routes a packet to the correct host or interface. After the packet reaches that host, the transport protocol and destination port identify the local service that should receive it. For example, TCP port 443 and UDP port 443 are distinct endpoints because TCP and UDP are different transport protocols.
How applications share one IP address
A host can run several network services on the same IP address when they listen on different ports. The operating system examines the packet's protocol and destination port, then demultiplexes the packet to the socket associated with that local endpoint.
In general, two applications cannot both exclusively bind the same local IP address, transport protocol, and port at the same time. Operating systems may provide controlled sharing mechanisms, but their behavior is implementation-specific.
- Web service: May listen on TCP port 443.
- Remote-access service: May listen on TCP port 22.
- DNS service: May use port 53 with UDP, TCP, or both.
Multiple simultaneous connections
For TCP, a connection is normally identified by the transport protocol, source IP address, source port, destination IP address, and destination port. This five-tuple lets a server accept many simultaneous connections to the same local IP address and port. Each accepted connection has separate communication state even though all clients reach the same listening service.
A socket is commonly described as the operating-system abstraction representing a communication endpoint. A server has a listening TCP socket, while each accepted TCP connection is represented by a separate connected socket.
