#Why this matters
Tools like curl and web browsers speak HTTP, yet many internal services, embedded devices, and CTF challenges communicate over raw TCP or custom binary protocols. Interactive challenges often enforce a two-second timer across twenty rounds, which makes manual nc typing impractical. Writing a Python client with the standard-library socket and struct modules lets you automate protocol exchanges accurately and inspect exact byte layouts.
#TCP is a stream, not a message box
Beginners often expect one sock.sendall() on the server to arrive in a single sock.recv(4096) on the client. TCP does not preserve message boundaries: the kernel may split a 200-byte banner across two recv() calls or merge two consecutive server lines into one read.
Always open connections with socket.create_connection((host, port), timeout=5.0) inside a with statement. That single helper resolves hostnames, handles IPv4 and IPv6, enforces a connect and read timeout, and closes the socket automatically when the block exits.
#Framing loops for interactive services
Because recv() can return fewer bytes than expected, every reliable client wraps reads in a small helper loop. For line-oriented services, accumulate bytes until the delimiter appears:
import socket
def recv_until(sock: socket.socket, delim: bytes = b"\n") -> bytes:
buf = bytearray()
while not buf.endswith(delim):
chunk = sock.recv(1)
if not chunk:
raise ConnectionError("peer closed connection before delimiter")
buf.extend(chunk)
return bytes(buf)
with socket.create_connection(("lab.local", 9001), timeout=5.0) as sock:
banner = recv_until(sock)
print(banner.decode("utf-8", errors="replace").strip())
sock.sendall(b"HELLO\n")
reply = recv_until(sock)
print(reply.decode("utf-8", errors="replace").strip())Notice two defensive habits in this snippet:
sock.sendall()loops internally until the entire buffer is queued, whereassock.send()may transmit only part of it.- Checking
if not chunk:detects an orderlyEOFfrom the server instead of spinning in an infinite loop.
For high-throughput text protocols, reading larger chunks into a persistent buffer object avoids one-byte-per-syscall overhead while keeping message boundaries intact.
#Packing binary protocols with struct
Binary protocols avoid text parsing overhead by sending fixed-width integers and byte strings. To decode them safely, both sides must agree on byte order (endianness) and field sizes. Network protocols standardise on big-endian order, written with ! in Python's struct format strings.
| Format | C Type | Size (bytes) | Typical use |
|---|---|---|---|
! |
(prefix) | 0 | Network (big-endian) byte order |
B |
uint8_t |
1 | Flags, version, status code |
H |
uint16_t |
2 | Port number, short length prefix |
I |
uint32_t |
4 | Message length, sequence ID |
4s |
char[4] |
4 | Fixed 4-byte protocol magic |
When reading length-prefixed binary frames, pair struct.unpack() with an exact-read helper that loops until n bytes are collected:
import socket
import struct
def recv_exact(sock: socket.socket, n: int) -> bytes:
buf = bytearray()
while len(buf) < n:
chunk = sock.recv(n - len(buf))
if not chunk:
raise ConnectionError(f"expected {n} bytes, got {len(buf)}")
buf.extend(chunk)
return bytes(buf)
payload = b"STATUS"
# 4-byte magic, 1-byte version, 2-byte big-endian payload length
header = struct.pack("!4sBH", b"CYBR", 1, len(payload))
with socket.create_connection(("192.0.2.10", 9002), timeout=5.0) as sock:
sock.sendall(header + payload)
resp_hdr = recv_exact(sock, 3)
status, body_len = struct.unpack("!BH", resp_hdr)
if body_len > 65535:
raise ValueError("frame length exceeds limit")
body = recv_exact(sock, body_len)
print(f"status={status} body={body!r}")Validating body_len before allocating or reading prevents a malformed server response from triggering excessive memory allocation.
#Defending and common mistakes
On the server side, never trust a client-supplied length integer blindly; enforce a strict maximum frame size before reading, wrap sensitive TCP protocols in TLS 1.3 (ssl.SSLContext), and set per-connection idle timeouts so slow clients cannot exhaust worker threads.
Common client-side bugs include:
- Calling
sock.recv(1024)once and assuming a complete message arrived. - Using
sock.send()instead ofsock.sendall()on large buffers. - Omitting
timeout, causing automated scans to freeze on dropped packets. - Leaving out
!instruct.pack(), which silently uses native little-endian order on x86 systems and breaks protocol alignment. - Passing Python
strobjects directly tosendall()instead of encoding tobytes.
#Summary
- TCP delivers an unframed stream of bytes, so clients must implement
recv_untilorrecv_exactloops aroundrecv(). - Always use
socket.create_connection(..., timeout=...)inside awithblock and transmit data usingsendall(). - Use
struct.pack()andstruct.unpack()with the!network byte-order prefix for binary headers and bounds-check incoming lengths. - Wrap plaintext TCP protocols in TLS 1.3 when transmitting credentials or sensitive telemetry.