Skip to content

Python Networking — Sockets, Requests, and HTTP

DodaTech Updated 2026-06-29 2 min read

Python excels at network programming. From low-level socket connections to high-level HTTP requests, the standard library covers everything you need. In this tutorial, you'll learn the networking tools every Python developer should know.

DodaTech's security tools use these techniques for port scanning, HTTP traffic analysis, and real-time network monitoring.

What You'll Learn

  • TCP and UDP socket programming
  • HTTP requests with the requests library
  • URL Parsing with urllib.parse
  • Building a simple HTTP server
  • Handling network errors and timeouts

TCP Socket Client

import socket

# Create a TCP socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect to a server
client.connect(("example.com", 80))

# Send HTTP request
request = "GET / HTTP/1.1
Host: example.com
Connection: close

"
client.send(request.encode())

# Receive response
response = b""
while True:
    data = client.recv(4096)
    if not data:
        break
    response += data

print(response.decode()[:500])  # First 500 chars
client.close()

TCP Socket Server

import socket

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("localhost", 9999))
server.listen(5)
print("Server listening on port 9999...")

# Handle one client
client, addr = server.accept()
print(f"Connection from {addr}")
data = client.recv(1024)
client.send(f"Echo: {data.decode()}".encode())
client.close()
server.close()

HTTP Requests with requests Library

import requests

# GET request
response = requests.get("https://api.github.com/users/python")
print(response.status_code)  # 200
print(response.json()["login"])  # python

# POST with JSON
payload = {"title": "foo", "body": "bar", "userId": 1}
response = requests.post("https://jsonplaceholder.typicode.com/posts", json=payload)
print(response.status_code)  # 201
print(response.json()["id"])  # 101

# Headers and authentication
headers = {"Authorization": "Bearer YOUR_TOKEN"}
response = requests.get("https://api.example.com/data", headers=headers)

# Error handling
try:
    response = requests.get("https://nonexistent.example.com", timeout=5)
    response.raise_for_status()  # Raises for 4xx/5xx
except requests.exceptions.RequestException as e:
    print(f"Request failed: {e}")

URL Parsing

from urllib.parse import urlparse, parse_qs

url = "https://user:pass@api.example.com:8080/search?q=python&page=2#results"
parsed = urlparse(url)

print(parsed.scheme)     # https
print(parsed.netloc)     # user:pass@api.example.com:8080
print(parsed.hostname)   # api.example.com
print(parsed.port)       # 8080
print(parsed.path)       # /search
print(parsed.query)      # q=python&page=2
print(parsed.fragment)   # results

# Parse query string into dict
params = parse_qs(parsed.query)
print(params)  # {'q': ['python'], 'page': ['2']}
print(params["q"][0])  # python

Practice Questions

  1. Build a simple port scanner that checks if common ports (22, 80, 443, 8080) are open on a host.

  2. Write a function that downloads a URL to a file with progress reporting.

  3. Build a TCP chat server that broadcasts messages to all connected clients.

  4. Use requests to consume a REST API with pagination (fetch all pages).

  5. Write a URL validator that parses a URL and returns its components.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro