Python › Networking Fundamentals
Sockets, port scanning, and DNS
Beneath HTTP sits raw networking, and Python’s socket module exposes it. Sockets let you build the things requests is too high-level for — port scanners, banner grabbers, custom protocol clients. This lesson covers TCP sockets and DNS, the network primitives behind recon tooling.
You'll learn to
- Open a TCP socket and test a port
- Grab service banners for fingerprinting
- Resolve DNS records for recon
A port scanner in fifteen lines
import socket
def check_port(host, port, timeout=2):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # IPv4, TCP
s.settimeout(timeout)
try:
s.connect((host, port)) # the handshake; raises if closed/filtered
try:
banner = s.recv(1024).decode(errors="ignore").strip()
except socket.timeout:
banner = ""
return True, banner
except (socket.timeout, ConnectionRefusedError, OSError):
return False, ""
finally:
s.close()
for port in [21, 22, 80, 443, 3389]:
up, banner = check_port("scanme.example", port)
if up:
print(f"{port} OPEN {banner[:60]}")
socket.socket(AF_INET, SOCK_STREAM) makes a TCP socket; connect performs the handshake — success means the port is open. recv reads any banner the service sends, which SSH, FTP, and SMTP announce on connect, giving version info for fingerprinting. The settimeout stops it hanging on filtered ports.
DNS for recon
import socket
socket.gethostbyname("example.com") # simple resolution
# Richer queries with dnspython (pip install dnspython):
import dns.resolver
for rtype in ["A", "MX", "TXT", "NS", "CNAME"]:
try:
for r in dns.resolver.resolve("example.com", rtype):
print(rtype, r.to_text())
except Exception:
pass
dnspython queries any record type. TXT records leak SPF and verification data; MX reveals mail infrastructure; CNAME chains expose third-party services and subdomain-takeover candidates.
Checkpoint
When you connect a TCP socket to an open port and call recv, why do services like SSH and FTP often return useful information immediately?
Many services send a banner — a greeting line announcing the software and often its version — as soon as a client connects, before any request. recv reads that banner, giving you service-version information for fingerprinting and vulnerability lookups, without sending anything yourself.
Try it yourself
Write a function that checks whether a single port is open on a host you’re authorised to scan, with a timeout, and grabs any banner. Test it against a few common ports and note which return banners.
Key takeaways
socket.connectperforms the TCP handshake — success means the port is open.recvgrabs service banners for version fingerprinting.dnspythonqueries A/MX/TXT/NS/CNAME records for recon.- Get the per-port logic right, then make it fast with concurrency.
Quick quiz
Next, packaging these pieces into polished, reusable security tools with proper command-line interfaces.