The Difference Between a Port and a Socket | Baeldung on Computer Science

1. Overview

In this tutorial, we’ll present the key differences between a port and a socket.

2. What Is a Port?

Port is a part of the transport layer and helps in network communication. A port is a logical identifier assigned to a process in order to identify that process uniquely in a network system. When two network devices communicate, they do so by sending packets to each other. Each packet received by a receiver device contains a port number that uniquely identifies the process where the packet needs to be sent.

Not all the network protocol uses a port for communication. For example, ICMP doesn’t use a port. On the other hand, protocols like TCP, UDP, HTTP utilize a port for communication.

Let’s look at an example. A client computer is requesting the server for a virtual connection with the port number \mathsf{23}. Telnet is a well-known protocol for establishing a remote connection over a TCP/IP and it uses port \mathsf{23}. Hence, the server acknowledges the request from the client and start a telnet connection:

port 1

3. What Is a Socket?

Two processes that are running on a computer or running on two different systems can communicate via a socket. A socket works as an inter-process communicator and seen as the endpoint of the process communication. For communication, the socket uses a file descriptor and is mainly employed in client-server applications.

A socket consists of the IP address of a system and the port number of a program within the system. The IP address corresponds to the system and the port number corresponds to the program where the data needs to be sent:

socket 1

Sockets can be classified into three categories: stream, datagram, and raw socket. Stream sockets use connection-oriented network point to send and receive data. This type of sockets generally utilizes TCP to permit processes to communicate with each other.

Datagram sockets use connectionless network protocols like UDP to allow process communication. Raw sockets are datagram oriented and allow the processes to use ICMP for communication purpose.

4. Port vs. Socket

We now know the basics of port and socket. Let’s see the differences between a port and a socket:

Rendered by QuickLaTeX.com

5. Conclusion

In this tutorial, we learned about ports and sockets in networking. We also presented some key differences between a port and a socket.