C

Python › Module 2 › Lesson 1

BeginnerModule 2Lesson 1/5

Socket Programming

Create TCP connections with Python sockets and understand host, port, and timeouts

15 min+53 XP3 quiz
Module progress1 of 5
ApplicationTransportInternetNetwork AccessEncapsulation ↓
TCP socket · Host · Port

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

1

socket.SOCK_STREAM typically means:

Multiple choice

Knowledge Check

2

True or False: settimeout helps scanners avoid hanging on dead ports.

True or False

Knowledge Check

3

s.connect((host, port)) success usually indicates:

Multiple choice

← Previous

Answer all 3 knowledge checks to continue. (0/3 answered)