30 Mins

7. Port Numbers & Socket Architecture

Port Number Categorization

Port numbers act as logical identifiers for network services, functioning as sub-addresses within an IP address. They are segmented into three distinct ranges to prevent collisions between system services, application software, and user-initiated sessions.

Well-known ports (0-1023) are assigned by IANA for core system services. Registered ports (1024-49151) are intended for common applications or vendor-specific software. Dynamic/Ephemeral ports (49152-65535) are assigned by the OS to client-side processes for temporary communication sessions.

Range CategoryPort Span
Well-Known0 - 1023
Registered1024 - 49151
Dynamic/Ephemeral49152 - 65535
Security Operator Note: Always check for rogue services listening on registered ports using 'ss -tulpn' to ensure no unexpected backdoors are active.
Text
nmap -p 0-1024 localhost
# Use netstat to identify ephemeral usage:
netstat -antp | grep ESTABLISHED

Understanding Socket Pair Bindings

A socket is the software abstraction for a network communication endpoint. A unique connection, or 'socket pair', is defined by a 5-tuple: (Source IP, Source Port, Destination IP, Destination Port, Protocol).

When an attacker or admin analyzes a connection, they are essentially extracting these five values. Without this unique combination, the kernel would be unable to demultiplex incoming packets to the correct application buffer.

Security Operator Note: In network forensics, the 5-tuple is your primary key for correlating logs between firewall entries and host-based connection states.
Python 3
import socket

def get_socket_pair():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('127.0.0.1', 0))
    print(f'Socket bound to: {s.getsockname()}')
    s.close()

get_socket_pair()

Implementing Non-Blocking Sockets

Standard socket operations like 'recv()' are blocking by default; they pause execution until data arrives. Non-blocking mode prevents the process from hanging by immediately raising an EWOULDBLOCK error if no data is available.

To manage multiple clients efficiently without spawning thousands of threads, we use selectors or asyncio. This allows a single thread to monitor many file descriptors, notifying the application only when a socket is ready for read or write operations.

Security Operator Note: Always wrap non-blocking calls in try-except blocks to catch BlockingIOError or EWOULDBLOCK.
Python 3
import socket, selectors

sel = selectors.DefaultSelector()
def accept(sock, mask):
    conn, addr = sock.accept()
    print(f'Connected to {addr}')
    conn.setblocking(False)

sock = socket.socket()
sock.bind(('localhost', 9999))
sock.listen()
sock.setblocking(False)
print('Server ready on port 9999')

Knowledge Check

Ready to test your understanding of 7. Port Numbers & Socket Architecture?

Back