Skip to content
We areTOP 1%

What are ports and sockets, and how do SOCK_STREAM and SOCK_DGRAM differ?

EasyConceptTCP & UDP
Track your progress
First attempt
Re-solve after a few days
Final pass before interviews

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_STREAM creates a TCP socket (a reliable byte stream; servers call listen() and accept()), while SOCK_DGRAM creates a UDP socket (separate messages sent with sendto(), 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.

More in TCP & UDP

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account