What are ports and sockets, and how do SOCK_STREAM and SOCK_DGRAM differ?
EasyConceptTCP & UDP
Answer
A port is a 16-bit number (0 to 65535) that identifies an application on a host. A socket is the endpoint a program uses to send and receive data, identified by an IP address plus a port, such as 192.168.1.5:51000. The operating system uses the port to hand each incoming segment to the right program.
- Well-known ports (0–1023) belong to standard services: 22 SSH, 25 SMTP, 53 DNS, 80 HTTP, 443 HTTPS. A client gets a temporary ephemeral port from the operating system.
- A TCP connection is identified by four values: source IP, source port, destination IP and destination port. That is why one server on port 443 can serve thousands of clients at once.
- In the sockets API,
SOCK_STREAMcreates a TCP socket (a reliable byte stream; servers calllisten()andaccept()), whileSOCK_DGRAMcreates a UDP socket (separate messages sent withsendto(), no connection).
Example: A minimal TCP client in Python:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TCP
s.connect(("example.com", 80)) # three-way handshake happens here
s.sendall(b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n")
print(s.recv(1024))
Using SOCK_DGRAM instead would create a UDP socket with no handshake.