Lecture by: Filip Gajic
Understanding network fundamentals is crucial for:
Seven Layers of Network Communication
# Physical Media Types
+-------------------+----------------+------------------+
| Media Type | Max Speed | Max Distance |
+-------------------+----------------+------------------+
| Cat5e | 1 Gbps | 100 meters |
| Cat6 | 10 Gbps | 55 meters |
| Fiber (Single) | 100 Gbps | 10 kilometers |
| Fiber (Multi) | 400 Gbps | 500 meters |
+-------------------+----------------+------------------+
def physical_layer_example():
"""Physical layer simulation"""
print("\n=== Layer 1 - Physical Layer Example ===")
def simulate_binary_transmission(data):
# Convert string to binary
binary = "".join(format(ord(i), "08b") for i in data)
print(f"Original data: {data}")
print(f"Binary representation: {binary}")
# Simulate Manchester encoding
manchester = ""
for bit in binary:
if bit == "1":
manchester += "10" # 1 becomes 10
else:
manchester += "01" # 0 becomes 01
print(f"Manchester encoded: {manchester}")
simulate_binary_transmission("Hello")
=== Layer 1 - Physical Layer Example ===
Original data: Hello
Binary representation: 0100100001100101011011000110110001101111
Manchester encoded: 01100101100101010110100101100110011010011010010101101001101001010110100110101010
# Ethernet Frame Structure
+----------------+----------------+------+----------------+
| Preamble | MAC Dest | MAC | Payload |
| (8 bytes) | (6 bytes) | Src | (46-1500 B) |
+----------------+----------------+------+----------------+
def data_link_layer_example():
"""Ethernet frame simulation"""
print("\n=== Layer 2 - Data Link Layer Example ===")
def create_ethernet_frame(dest_mac, source_mac, payload):
# Simulate Ethernet frame structure
frame = struct.pack(
"!6s6s2s",
bytes.fromhex(dest_mac.replace(":", "")),
bytes.fromhex(source_mac.replace(":", "")),
b"\x08\x00", # EtherType (IPv4)
) + payload
return frame
# Example usage
dest_mac = "00:11:22:33:44:55"
source_mac = "66:77:88:99:aa:bb"
payload = b"Sample Ethernet frame payload"
frame = create_ethernet_frame(dest_mac, source_mac, payload)
print(f"Ethernet Frame (hex): {frame.hex()}")
=== Layer 2 - Data Link Layer Example ===
Ethernet Frame (hex): 00112233445566778899aabb080053616d706c652045746865726e6574206672616d65207061796c6f6164
# IP Routing Table Example
Destination Gateway Genmask Flags Interface
0.0.0.0 192.168.1.1 0.0.0.0 UG eth0
192.168.1.0 0.0.0.0 255.255.255.0 U eth0
172.16.0.0 192.168.1.100 255.240.0.0 UG eth0
def network_layer_example():
"""IP addressing and routing example"""
print("\n=== Layer 3 - Network Layer Example ===")
def get_ip_info():
try:
hostname = socket.gethostname()
ip_address = socket.gethostbyname(hostname)
print(f"Hostname: {hostname}")
print(f"IP Address: {ip_address}")
except socket.gaierror:
print("Could not resolve hostname to IP")
print("Using example IP for demonstration")
# Simulate routing table
print("\nSimulated Routing Table:")
routes = [
{
"destination": "0.0.0.0/0",
"gateway": "192.168.1.1",
"interface": "eth0"
},
{
"destination": "192.168.1.0/24",
"gateway": "-",
"interface": "eth0"
},
{
"destination": "10.0.0.0/8",
"gateway": "192.168.1.254",
"interface": "eth0"
}
]
for route in routes:
print(
f"Dest: {route['destination']:<15} "
f"Gateway: {route['gateway']:<15} "
f"Interface: {route['interface']}"
)
get_ip_info()
=== Layer 3 - Network Layer Example ===
Hostname: MacBook-Pro.local
IP Address: 127.0.0.1
Simulated Routing Table:
Dest: 0.0.0.0/0 Gateway: 192.168.1.1 Interface: eth0
Dest: 192.168.1.0/24 Gateway: - Interface: eth0
Dest: 10.0.0.0/8 Gateway: 192.168.1.254 Interface: eth0
// TCP Connection Example
socket.connect({
port: 80,
host: 'example.com',
keepAlive: true,
timeout: 3000
});
// UDP Datagram Example
const dgram = require('dgram');
const client = dgram.createSocket('udp4');
const message = Buffer.from('Game state update');
client.send(message, 0, message.length, 12345, 'gameserver.com', (err) => {
if (err) console.error('Failed to send packet');
// No connection state to maintain
// No delivery guarantee
// Just fire and forget
});
def transport_layer_example():
"""TCP and UDP socket examples"""
print("\n=== Layer 4 - Transport Layer Example ===")
def tcp_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("localhost", 12345))
server_socket.listen(1)
print("TCP Server listening on port 12345")
return server_socket
def udp_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(("localhost", 12346))
print("UDP Server listening on port 12346")
return server_socket
# Example usage
tcp_sock = tcp_server()
udp_sock = udp_server()
print("Transport layer sockets created")
=== Layer 4 - Transport Layer Example ===
TCP Server listening on port 12345
UDP Server listening on port 12346
Transport layer sockets created
// Session Establishment Example
Session.establish({
type: "NetBIOS",
authentication: "Kerberos",
recovery: true,
checkpointing: {
interval: "5min"
}
});
def session_layer_example():
"""Simple session management example"""
print("\n=== Layer 5 - Session Layer Example ===")
class SessionManager:
def __init__(self):
self.sessions = {}
def create_session(self, user_id):
session_id = binascii.hexlify(os.urandom(16)).decode()
self.sessions[session_id] = {
"user_id": user_id,
"created_at": time.time(),
"active": True
}
return session_id
def check_session(self, session_id):
return self.sessions.get(session_id, {}).get("active", False)
# Usage example
session_mgr = SessionManager()
session_id = session_mgr.create_session("user123")
print(f"Created session: {session_id}")
print(f"Session active: {session_mgr.check_session(session_id)}")
=== Layer 5 - Session Layer Example ===
Created session: 07af8fa6ed9c8d348c9197fb979172a3
Session active: True
// SSL/TLS Handshake Example
Client -> Server: ClientHello
Server -> Client: ServerHello, Certificate
Client -> Server: ClientKeyExchange
Both: Generate Session Keys
def presentation_layer_example():
"""Data encryption/decryption example"""
print("\n=== Layer 6 - Presentation Layer Example ===")
key = Fernet.generate_key()
cipher_suite = Fernet(key)
message = b"Sensitive data to encrypt"
encrypted_data = cipher_suite.encrypt(message)
print(f"Original message: {message}")
print(f"Encrypted data: {encrypted_data}")
decrypted_data = cipher_suite.decrypt(encrypted_data)
print(f"Decrypted data: {decrypted_data}")
=== Layer 6 - Presentation Layer Example ===
Original message: b'Sensitive data to encrypt'
Encrypted data: b'gAAAAABnvZ4lgK2gSY3aPk7XKFGFRLA3HuDaD-5BsEN-3pJ4wo0fCabFZDr67zTa9PgEXWrxM-WeYAWVvLD8XDYuU8FTovHiRriyvpUwBWhxP4pqlhx3Ryo='
Decrypted data: b'Sensitive data to encrypt'
# HTTP Request Example
GET /index.html HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0
Accept: text/html
def application_layer_example():
"""HTTP Request using requests library"""
print("\n=== Layer 7 - Application Layer Example ===")
try:
response = requests.get("https://api.github.com")
print(f"Status Code: {response.status_code}")
print(f"Headers: {dict(response.headers)}")
except requests.RequestException as e:
print(f"Request failed: {e}")
=== Layer 7 - Application Layer Example ===
Status Code: 200
Headers: {
'Content-Type': 'application/json',
'Server': 'GitHub.com',
'Status': '200 OK',
'Cache-Control': 'public, max-age=60',
'Vary': 'Accept, Authorization, Cookie',
'ETag': 'W/"a0d3712a7766d5f1fc51fcd0dccd709d"',
'X-GitHub-Request-Id': '5F5D:0000:0000:0000:0000:0000:0000:0000',
'X-Runtime-rack': '0.024121',
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'deny',
'X-XSS-Protection': '1; mode=block',
'X-OAuth-Scopes': '',
'X-Accepted-OAuth-Scopes': '',
'X-GitHub-Media-Type': 'github.v3',
'Access-Control-Allow-Origin': '*',
'Access-Control-Expose-Headers': 'ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Used, X-OAuth-Scopes, X-Accepted-OAuth-Scopes',
'Access-Control-Allow-Methods': 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Credentials': 'true',
'Strict-Transport-Security': 'max-age=31536000; includeSubdomains; preload',
'X-Next-Page': 'https://api.github.com/user/repos?page=2',
'Link': '; rel="next"',
'Content-Security-Policy': "default-src 'none'",
'X-OAuth-Client-Id': 'Iv1.a5d5f5d5f5d5f5d5',
'X-OAuth-Client-Secret': 's5d5f5d5f5d5f5d5f5d5f5d5f5d5f5d5'
}
// Private IP Ranges (RFC 1918)
10.0.0.0/8 # Large Enterprise
172.16.0.0/12 # Medium Network
192.168.0.0/16 # Small Network
// Problematic Design ❌
Development: 10.0.0.0/8
Staging: 10.0.0.0/8 // Overlap!
Production: 10.0.0.0/8 // Overlap!
// Optimized Design ✅
Development: 10.15.0.0/16 // 10.15.0.0 - 10.15.255.255
Staging: 10.16.0.0/16 // 10.16.0.0 - 10.16.255.255
Production: 10.17.0.0/16 // 10.17.0.0 - 10.17.255.255
Benefits:
Key considerations:
# Application Networks (10.0.0.0/8)
# HeadEndSystem
hes-development: 10.4.0.0/16
hes-development-test: 10.1.0.0/16
hes-staging: 10.2.0.0/16
hes-production: 10.3.0.0/16
# PaymentHub
payhub-development: 10.5.0.0/16
payhub-development-test: 10.6.0.0/16
payhub-staging: 10.7.0.0/16
payhub-production: 10.8.0.0/16
# Integration Networks (172.16.0.0/12)
# IPSec Tunnel
hes-onomondo-ipsec: 172.16.0.0/24 # VPN connectivity
# Business Analytics
hes-ba: 172.16.1.0/24 # Analytics services
module "vnet" {
source = "../../../1_modules/network"
vnet_name = "VirtualNetwork"
location = local.location
resource_group_name = local.resource_group_name
address_space = [local.address_space]
subnets = {
"default" = {
address_prefixes = ["${local.address_prefix}.0.0/24"]
}
"app-gateway" = {
address_prefixes = ["${local.address_prefix}.1.0/24"]
}
"database-subnet" = {
address_prefixes = ["${local.address_prefix}.2.0/24"]
service_endpoints = ["Microsoft.Storage"]
service_delegation = {
name = "Microsoft.DBforPostgreSQL/flexibleServers"
actions = [
"Microsoft.Network/virtualNetworks/subnets/join/action"
]
}
}
}
}
# Basic VNet Configuration
module "vnet" {
source = "../modules/network"
vnet_name = "VirtualNetwork"
}
subnets = {
"default" = {
address_prefixes = ["${local.address_prefix}.0.0/24"]
}
"app-gateway" = {
address_prefixes = ["${local.address_prefix}.1.0/24"]
}
"dlms-db-subnet" = {
address_prefixes = ["${local.address_prefix}.2.0/24"]
service_endpoints = [
"Microsoft.Storage"
]
service_delegation = {
name = "Microsoft.DBforPostgreSQL/flexibleServers"
actions = [
"Microsoft.Network/virtualNetworks/subnets/join/action"
]
}
}
"container-apps" = {
address_prefixes = ["${local.address_prefix}.6.0/24"]
service_delegation = {
name = "Microsoft.App/environments"
actions = [
"Microsoft.Network/virtualNetworks/subnets/join/action"
]
}
}
}
// Network Security Group Rule Example
{
"name": "allow-https",
"priority": 100,
"direction": "Inbound",
"access": "Allow",
"protocol": "Tcp",
"sourcePortRange": "*",
"destinationPortRange": "443",
"sourceAddressPrefix": "*",
"destinationAddressPrefix": "VirtualNetwork"
}
monitoring:
metrics:
- bandwidth_utilization
- latency
- packet_loss
- error_rate
alerts:
- threshold: 80%
metric: bandwidth
action: notify_team
Thank you for your attention and let's grab a beer while discussing your questions.