Chapter 4: Python for Network Programming

Use Python to communicate with network devices, ports, sockets and protocols for safe cyber security automation and network analysis.

SocketsPortsDNS LookupHTTP RequestsNetwork Automation
Socket
Programming
Port
Checking
Protocol
Testing
Network
Reports

4.1 Chapter Overview

Python network programming allows security professionals to interact with network services, resolve domain names, check ports, communicate with servers, collect banners, send HTTP requests and automate network troubleshooting.

In cyber security, Python network scripts are useful for defensive tasks such as checking whether approved services are running, validating firewall changes, testing internal lab servers, monitoring web availability and generating network status reports.

Learning Outcome: By the end of this chapter, learners should be able to use Python safely to communicate with network devices, ports, sockets and protocols in controlled environments.
Python Script
Socket / Request
Network Service
Response
Security Report

4.2 Learning Objectives

  • Understand what network programming means in cyber security.
  • Use Python sockets to connect to local and remote services.
  • Resolve domain names into IP addresses.
  • Check whether selected ports are open on authorized systems.
  • Build simple TCP client and server programs for lab testing.
  • Use Python to send HTTP requests and inspect responses.
  • Handle network errors and timeouts safely.
  • Create simple network status reports.
  • Understand legal and ethical limitations of network scripting.

4.3 What is Network Programming?

Network programming is the process of writing programs that communicate over a network. Python can open connections, send data, receive responses and process network results.

TaskPython CapabilitySecurity Use
Resolve domainsocket.gethostbyname()Check where a domain points.
Check service portsocket.connect_ex()Validate approved ports.
Send HTTP requestrequests.get()Check website availability.
Create lab serversocket.bind() and listen()Learn client-server communication.
Log resultscsv or text fileGenerate network status report.
Important: Only run network scripts on systems you own, manage or have written permission to test.

4.4 Understanding Sockets

A socket is an endpoint for network communication. It allows a program to send and receive data through an IP address and port.

Socket = IP Address + Port + Protocol

TCP Socket Connection Example

import socket

target_host = "example.com"
target_port = 80

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

client.settimeout(5)

result = client.connect_ex((target_host, target_port))

if result == 0:
    print("Connection successful")
else:
    print("Connection failed")

client.close()

Line-by-Line Explanation

CodeExplanation
socket.AF_INETUses IPv4 addressing.
socket.SOCK_STREAMUses TCP communication.
settimeout(5)Stops waiting after 5 seconds.
connect_ex()Attempts connection and returns status code.

4.5 DNS Lookup with Python

Python can resolve domain names to IP addresses using the socket library.

import socket

domain = "perakskills.com"

try:
    ip_address = socket.gethostbyname(domain)
    print(domain, "resolves to", ip_address)

except socket.gaierror:
    print("DNS lookup failed")

Multiple Domain Lookup

import socket

domains = ["perakskills.com", "example.com", "openai.com"]

for domain in domains:
    try:
        ip_address = socket.gethostbyname(domain)
        print(domain, "->", ip_address)

    except socket.gaierror:
        print(domain, "-> DNS lookup failed")
Security Use: DNS lookup scripts can help analysts verify whether suspicious domains resolve successfully.

4.6 Safe Port Checking with Python

A port checker tests whether selected ports are open on an authorized host. This is useful for validating internal systems, lab servers and firewall changes.

Ethical Rule: Do not scan public systems or networks without written permission. The examples here are for your own computer, lab machines or authorized environments only.

Check Selected Ports on Localhost

import socket

target = "127.0.0.1"
ports = [22, 80, 443, 3306, 3389]

for port in ports:
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.settimeout(1)

    result = client.connect_ex((target, port))

    if result == 0:
        print("Port", port, "is open")
    else:
        print("Port", port, "is closed")

    client.close()

Function-Based Port Checker

import socket

def check_port(host, port):
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.settimeout(2)

    result = client.connect_ex((host, port))

    client.close()

    if result == 0:
        return "Open"
    else:
        return "Closed"

host = "127.0.0.1"

for port in [80, 443, 8080]:
    status = check_port(host, port)
    print(host, port, status)

4.7 Banner Grabbing Concept

Banner grabbing means connecting to a service and reading information it sends back. Administrators use banner review to identify outdated services in controlled environments.

import socket

host = "example.com"
port = 80

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.settimeout(5)

try:
    client.connect((host, port))

    request = b"HEAD / HTTP/1.1\r\nHost: example.com\r\n\r\n"

    client.send(request)

    response = client.recv(1024)

    print(response.decode(errors="ignore"))

except Exception as error:
    print("Error:", error)

finally:
    client.close()
Security Use: Banner information may reveal server type or version. In real organizations, this should be used only with authorization and for defensive assessment.

4.8 HTTP Requests with Python

The requests library makes HTTP and HTTPS communication easier than raw sockets.

Install requests

pip install requests

Check Website Status

import requests

url = "https://perakskills.com"

try:
    response = requests.get(url, timeout=5)

    print("Status Code:", response.status_code)
    print("Content Type:", response.headers.get("Content-Type"))

except requests.exceptions.RequestException as error:
    print("Request failed:", error)

Check Multiple Websites

import requests

websites = [
    "https://perakskills.com",
    "https://example.com"
]

for website in websites:
    try:
        response = requests.get(website, timeout=5)
        print(website, "Status:", response.status_code)

    except requests.exceptions.RequestException:
        print(website, "Unavailable")

4.9 Simple TCP Server and Client for Lab Testing

Client-server examples help learners understand how network communication works. Run these examples only on your own computer or lab network.

TCP Server - Save as server.py

import socket

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server.bind(("127.0.0.1", 9000))

server.listen(1)

print("Server listening on 127.0.0.1:9000")

connection, address = server.accept()

print("Connection from:", address)

message = connection.recv(1024).decode()

print("Client said:", message)

connection.send(b"Message received by PDTC server")

connection.close()
server.close()

TCP Client - Save as client.py

import socket

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

client.connect(("127.0.0.1", 9000))

client.send(b"Hello from PDTC client")

response = client.recv(1024)

print(response.decode())

client.close()
How to Test: Open two terminals. Run server.py first. Then run client.py. The client and server should exchange messages.

4.10 UDP Communication Example

UDP is connectionless and does not require a handshake. It is used by protocols such as DNS and DHCP.

UDP Server

import socket

server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

server.bind(("127.0.0.1", 9001))

print("UDP server listening on 127.0.0.1:9001")

data, address = server.recvfrom(1024)

print("Received from:", address)
print("Message:", data.decode())

server.sendto(b"UDP message received", address)

server.close()

UDP Client

import socket

client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

client.sendto(b"Hello UDP server", ("127.0.0.1", 9001))

data, address = client.recvfrom(1024)

print(data.decode())

client.close()

4.11 Generate Network Status Report

Security analysts often need reports showing which approved services are reachable.

import socket
import csv
from datetime import datetime

def check_port(host, port):
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.settimeout(2)
    result = client.connect_ex((host, port))
    client.close()

    if result == 0:
        return "Open"
    return "Closed"

host = "127.0.0.1"
ports = [22, 80, 443, 8080, 9000]

with open("network_status_report.csv", "w", newline="", encoding="utf-8") as file:
    writer = csv.writer(file)
    writer.writerow(["Timestamp", "Host", "Port", "Status"])

    for port in ports:
        status = check_port(host, port)
        writer.writerow([datetime.now(), host, port, status])
        print(host, port, status)

print("Report created: network_status_report.csv")

4.12 Handling Network Errors

Network scripts must handle timeouts, DNS failures and connection errors.

import socket

host = "unknown-domain-example.invalid"
port = 80

try:
    ip = socket.gethostbyname(host)
    print("IP Address:", ip)

    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.settimeout(3)
    client.connect((ip, port))
    print("Connected successfully")

except socket.gaierror:
    print("DNS resolution failed")

except socket.timeout:
    print("Connection timed out")

except ConnectionRefusedError:
    print("Connection refused")

except Exception as error:
    print("Unexpected error:", error)

finally:
    print("Network check completed")

4.13 Mini Network Toolkit Example

This small toolkit combines DNS lookup, port checking and website status checking.

import socket
import requests

def dns_lookup(domain):
    try:
        return socket.gethostbyname(domain)
    except socket.gaierror:
        return "DNS failed"

def check_port(host, port):
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.settimeout(2)
    result = client.connect_ex((host, port))
    client.close()
    return "Open" if result == 0 else "Closed"

def check_website(url):
    try:
        response = requests.get(url, timeout=5)
        return response.status_code
    except requests.exceptions.RequestException:
        return "Unavailable"

print("DNS:", dns_lookup("perakskills.com"))
print("Port 443:", check_port("perakskills.com", 443))
print("Website:", check_website("https://perakskills.com"))

4.14 Interactive Port Meaning Checker

Enter a port number to see common service information.

Click Check Port.

4.15 Legal and Ethical Use

Important: Network programming must be used responsibly. Do not scan, test, connect to, overload or collect information from systems without authorization.
AllowedNot Allowed
Testing your own localhost lab server.Scanning public IP addresses without permission.
Checking approved company systems.Bypassing access controls.
Generating internal service status reports.Collecting banners from unauthorized systems.
Learning client-server communication in a lab.Disrupting services or causing denial of service.

4.16 Practical Activities

Activity 1: DNS Lookup

Write a Python script to resolve three domain names into IP addresses.

Activity 2: Local Port Check

Check selected ports on 127.0.0.1 and record whether they are open or closed.

Activity 3: Website Status

Use requests to check whether approved websites return HTTP status code 200.

Activity 4: TCP Client and Server

Run the TCP server and client examples using two terminals.

Mini Project

Create a network status reporting tool that checks DNS, selected ports and website status, then saves results to CSV.

4.17 Interactive Final Assessment Quiz

Each correct answer gives +1 mark. Each wrong answer gives -0.5 mark.

1. A socket is an endpoint for network communication.

2. Which Python library is used for low-level socket programming?

3. socket.gethostbyname() can resolve a domain to an IP address.

4. TCP uses connection-oriented communication.

5. Which library is commonly used for HTTP requests in Python?

6. connect_ex() can be used to check whether a TCP port is reachable.

7. UDP is connectionless.

8. It is ethical to scan any public system without permission.

9. Timeouts help prevent a network script from waiting forever.

10. A CSV file can be used to store network status results.

Your Score: 0

4.18 Chapter Summary

In this chapter, learners studied Python for network programming, including sockets, DNS lookup, port checking, HTTP requests, TCP client-server communication, UDP communication, error handling and network status reporting.

Remember: Python network programming is powerful for defensive cyber security automation, but it must be used only in authorized and ethical environments.