Python for Networking: Sockets & Requests ππ

Python provides powerful tools for network programming. Two key modules are:
πΉ Sockets β For low-level network communication (TCP, UDP).
πΉ Requests β For making HTTP requests (REST APIs, web scraping).
Letβs dive into both! π
1οΈβ£ Sockets β Low-Level Networking ποΈ
πΉ Sockets allow two computers to communicate over a network.
πΉ Supports TCP (reliable) & UDP (fast, no connection) protocols.
Installing the socket Module
β
No installation needed! socket is built into Python.
Basic TCP Server & Client
β
Server (Listens for Connections)
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("127.0.0.1", 12345)) # Bind to local IP & port
server_socket.listen(1)
print("Server is listening...")
conn, addr = server_socket.accept()
print(f"Connected by {addr}")
conn.sendall(b"Hello from Server!")
conn.close()
server_socket.close()
β
Client (Connects to Server)
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("127.0.0.1", 12345))
data = client_socket.recv(1024)
print("Received:", data.decode())
client_socket.close()
Key Features of Sockets
β Low-level control over networking
β Used in chat apps, game servers, and IoT
β Can handle both TCP & UDP communication
2οΈβ£ Requests β Making HTTP Requests π
πΉ Requests is a simple way to interact with web APIs.
πΉ Used for web scraping, API calls, automation.
Installing Requests
pip install requests
Making a Basic HTTP Request
import requests
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
print(response.json()) # Convert response to JSON
Sending Data via POST Request
import requests
data = {"title": "Python", "body": "Networking with Requests", "userId": 1}
response = requests.post("https://jsonplaceholder.typicode.com/posts", json=data)
print("Response Code:", response.status_code)
print("Response Data:", response.json())
Handling Headers & Authentication
headers = {"Authorization": "Bearer YOUR_ACCESS_TOKEN"}
response = requests.get("https://api.example.com/data", headers=headers)
print(response.json())
Downloading a File with Requests
response = requests.get("https://example.com/file.pdf")
with open("downloaded_file.pdf", "wb") as file:
file.write(response.content)
Key Features of Requests
β Easy to use for web requests
β Supports authentication, headers, & sessions
β Great for REST API interaction
3οΈβ£ Sockets vs. Requests β When to Use What?
Feature Sockets Requests
Type Low-level networking High-level HTTP requests
Use Case Real-time chat, game servers APIs, web scraping, automation
Protocol TCP, UDP HTTP, HTTPS
Ease of Use More complex Very simple
Date: 2025-03-24 00:00:00.000000