Network programming: sockets, SDN, and security
Network programming and sockets
The exam tests the socket module at the syscall level, plus awareness of software-defined networking (control plane vs data plane, OpenFlow-style controllers) and secure-by-default configuration.
Core rules. socket.socket(AF_INET, SOCK_STREAM) is TCP, SOCK_DGRAM is UDP. Servers bind((host, port)), listen(n), then loop on accept() which returns (conn, addr). Clients connect(). Use sendall() - send() may transmit fewer bytes. recv(n) returns at most n bytes and b"" once the peer closes; TCP is a byte stream with no message boundaries, so you must frame messages yourself (length prefix, delimiter via makefile().readline(), or fixed size). setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) avoids TIME_WAIT bind errors. getaddrinfo() resolves names portably; selectors multiplexes many sockets without threads.
Security. Wrap sockets with ssl.create_default_context() and context.wrap_socket(sock, server_hostname=host); keep check_hostname and CERT_REQUIRED on. Compare secrets with hmac.compare_digest. Never trust a length field arriving from the network without bounding it.
Worked example
A TCP client reading a known byte count:
chunks, need = [], 4096
while need:
b = sock.recv(need)
if not b: break
chunks.append(b); need -= len(b)
The loop exists because one recv returning 100 bytes does not mean the peer sent 100 bytes and stopped - the remainder may still be in flight, so a single recv plus decode() can truncate the payload.
Traps
send()instead ofsendall()under load.- Sending
strwithout.encode(), or decodingbyteswithout.decode(). - Reusing a closed socket; prefer
with socket.socket(...) as s:. - Treating UDP
recvfromas reliable or ordered. - Disabling certificate verification to "fix" an SSL error.