Networking & Cybersecurity – Part 8: Full Python
Code Examples
1. TCP Chat Server and Client
Below is a minimal chat system for two of your own computers on the same network.
Server (save as chat_server.py):
--------------------------------
import socket
HOST = '' # empty means all interfaces
PORT = 5000 # port to listen on
server = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link]((HOST, PORT))
[Link](1)
print("Server listening on port", PORT)
conn, addr = [Link]()
print("Connected by", addr)
while True:
data = [Link](1024)
if not data:
break
print("Client:", [Link]())
msg = input("You: ")
[Link]([Link]())
[Link]()
Client (save as chat_client.py):
--------------------------------
import socket
HOST = '192.168.1.X' # replace with server's IP
PORT = 5000
client = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link]((HOST, PORT))
while True:
msg = input("You: ")
[Link]([Link]())
data = [Link](1024)
print("Server:", [Link]())
Explanation:
• [Link]() creates a TCP socket.
• [Link]() attaches to a port.
• [Link]() waits for a client.
• [Link]() receives data; [Link]() sends data.
2. Scapy Traffic Visualizer (Basic)
This captures packets for 10 seconds and counts protocols.
from [Link] import sniff
from collections import Counter
from time import time
counter = Counter()
start = time()
def count_protocol(packet):
proto = [Link]().split()[0]
counter[proto] += 1
sniff(timeout=10, prn=count_protocol)
print("Protocol counts:", counter)
Explanation:
• Counter() stores protocol counts.
• sniff(timeout=10) captures packets for 10 seconds.
• [Link]() gives a quick protocol name.
3. File Encryption with cryptography
Encrypt any file with a password-like key.
from [Link] import Fernet
# Generate a key and save it (run once)
key = Fernet.generate_key()
with open('[Link]', 'wb') as keyfile:
[Link](key)
# Load the key
with open('[Link]', 'rb') as keyfile:
key = [Link]()
f = Fernet(key)
# Encrypt a file
with open('[Link]', 'rb') as original_file:
data = original_file.read()
encrypted = [Link](data)
with open('[Link]', 'wb') as encrypted_file:
encrypted_file.write(encrypted)
Explanation:
• Fernet.generate_key() creates a random secret key.
• [Link](data) produces encrypted bytes.
• Only someone with the same key can decrypt it.