Python › Module 2 › Lesson 1
Socket Programming
Create TCP connections with Python sockets and understand host, port, and timeouts
Opening
Port scanners are socket loops
When you “check if port 22 is open,” your computer tries a TCP handshake. Python’s socket module lets you attempt that connection and see if it succeeds—exactly what beginner scanners do.
1. TCP Connect Attempt
Try connecting to localhost:22import socket host = "127.0.0.1" port = 22 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(1.0) try: s.connect((host, port)) print("open") except OSError: print("closed/filtered") finally: s.close()
import socket
host = "127.0.0.1"
port = 22
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1.0)
try:
s.connect((host, port))
print("open")
except OSError:
print("closed/filtered")
finally:
s.close()2. Pieces That Matter
AF_INET + SOCK_STREAM
IPv4 TCP—the usual combo for simple scanners.
timeout
Stops your script from hanging forever on blackholed ports.
connect()
Success ≈ port appears open from your vantage point.
Scope lock
Keep host = "127.0.0.1" until you have a lab IP you own. Mistakes at scale are still attacks.
Knowledge Check
socket.SOCK_STREAM typically means:
Multiple choice
Knowledge Check
True or False: settimeout helps scanners avoid hanging on dead ports.
True or False
Knowledge Check
s.connect((host, port)) success usually indicates:
Multiple choice