Networking - CameronAuler/python-devops GitHub Wiki

Python provides several libraries for network programming, including:

  • socket module for low-level networking.
  • requests module for making HTTP requests.
  • http.server module for building simple web servers.

Table of Contents

Socket Programming

The socket module enables direct communication between computers over a network using TCP/IP or UDP protocols.

Creating a Basic TCP Server & Client

This is mainly used for chat applications, file transfers, and network services.

Server

import socket

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # Create a TCP socket
server_socket.bind(("localhost", 12345))  # Bind to localhost and port 12345
server_socket.listen(1)  # Listen for connections

print("Server is waiting for a connection...")
conn, addr = server_socket.accept()  # Accept connection from client
print(f"Connected by {addr}")

data = conn.recv(1024)  # Receive data (max 1024 bytes)
print("Received:", data.decode())

conn.sendall(b"Hello, Client!")  # Send response to client
conn.close()  # Close connection

Client

import socket

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # Create a TCP socket
client_socket.connect(("localhost", 12345))  # Connect to server

client_socket.sendall(b"Hello, Server!")  # Send data
response = client_socket.recv(1024)  # Receive response

print("Server response:", response.decode())
client_socket.close()

Output

# Output (Server):
Server is waiting for a connection...
Connected by ('127.0.0.1', <port_number>)
Received: Hello, Server!

# Output (Client):
Server response: Hello, Client!

Creating a UDP Server & Client

UDP is faster than TCP but does not guarantee message delivery. This is mainly used for ideal for real-time gaming, VoIP, and lightweight data transfer.

Server

import socket

server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # Create a UDP socket
server_socket.bind(("localhost", 12345))  # Bind to localhost and port 12345

print("UDP Server is waiting for data...")
data, addr = server_socket.recvfrom(1024)  # Receive data
print(f"Received from {addr}: {data.decode()}")

server_socket.sendto(b"Hello, UDP Client!", addr)  # Send response

Client

import socket

client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # Create a UDP socket
client_socket.sendto(b"Hello, UDP Server!", ("localhost", 12345))  # Send data

data, addr = client_socket.recvfrom(1024)  # Receive response
print("Server response:", data.decode())
client_socket.close()

Output

# Output (Server):
UDP Server is waiting for data...
Received from ('127.0.0.1', <port_number>): Hello, UDP Server!

# Output (Client):
Server response: Hello, UDP Client!

HTTP Requests (requests)

The requests module provides a simple API for making HTTP requests.

Installing the requests Module

pip install requests

GET requests

GET requests are primarily used for fetching data from APIs, web scraping, and website monitoring.

import requests

response = requests.get("https://api.github.com")
print(response.status_code)  # HTTP Status Code
print(response.json())  # Print JSON response
# Output:
200
{...JSON data from GitHub API...}

POST Requests

Post requests are mainly used for form submissions, API authentication, and data uploads.

import requests

data = {"username": "user", "password": "pass"}
response = requests.post("https://httpbin.org/post", json=data)

print(response.status_code)
print(response.json())  # Print response

Handling Request Headers & Parameters

Mainly used for web scraping, API requests, and authentication.

import requests

headers = {"User-Agent": "MyApp"}
params = {"q": "python"}

response = requests.get("https://www.google.com/search", headers=headers, params=params)
print(response.url)  # Print final URL after adding parameters

Basic Web Server

The http.server module allows running a basic HTTP server.

Running a Simple HTTP Server

This is mainly used for serving static files for local development.

from http.server import SimpleHTTPRequestHandler
from socketserver import TCPServer

PORT = 8000
handler = SimpleHTTPRequestHandler

with TCPServer(("localhost", PORT), handler) as httpd:
    print(f"Serving at http://localhost:{PORT}")
    httpd.serve_forever()

Creating a Custom HTTP Server

Handle custom requests by subclassing BaseHTTPRequestHandler. This is mainly used for creating custom API endpoints and local development servers.

from http.server import BaseHTTPRequestHandler, HTTPServer

class SimpleServer(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)  # Send HTTP 200 response
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(b"<h1>Hello, World!</h1>")  # Send response content

server_address = ("localhost", 8080)
httpd = HTTPServer(server_address, SimpleServer)
print("Server running at http://localhost:8080")
httpd.serve_forever()
# Output:
Server running at http://localhost:8080
⚠️ **GitHub.com Fallback** ⚠️