PYTHON · Code cell
# =====================================================================
# N14 | Code cell 02 | IPv6 Addressing & Subnetting
# Purpose: 3. Implementation Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
#!/usr/bin/env python3
"""Bounded, dependency-free local protocol exercises. No external hosts or raw sockets."""
import argparse, ipaddress, json, socket, struct, threading, urllib.request
from http.server import BaseHTTPRequestHandler, HTTPServer
# Define the reusable operation check; keep its logic separate from the trial.
def check(ok, label, evidence):
if not ok: raise AssertionError(label)
return dict(check=label,passed=True,evidence=evidence)
# Define the reusable operation exchange; keep its logic separate from the trial.
def exchange(request, responder, family=socket.AF_INET):
host='::1' if family==socket.AF_INET6 else '127.0.0.1'
with socket.socket(family,socket.SOCK_DGRAM) as server, socket.socket(family,socket.SOCK_DGRAM) as client:
server.bind((host,0)); client.settimeout(1); server.settimeout(1)
client.sendto(request,server.getsockname())
data,peer=server.recvfrom(4096); response=responder(data)
if response is None: return None
server.sendto(response,peer); received,origin=client.recvfrom(4096)
assert origin[:2]==server.getsockname()[:2]
return received
# Define the reusable operation checksum; keep its logic separate from the trial.
def checksum(data):
if len(data)%2:data+=b'\0'
total=sum(struct.unpack('!'+str(len(data)//2)+'H',data))
while total>>16:total=(total&0xffff)+(total>>16)
return (~total)&0xffff
# Define the reusable operation packet; keep its logic separate from the trial.
def packet():
h=bytearray.fromhex('4500003c0001400040110000c0000201c0000202')
struct.pack_into('!H',h,10,checksum(h)); bad=bytearray(h);bad[8]^=1
return [check(checksum(h)==0,'Valid IPv4 header',h.hex()),check(checksum(bad)!=0,'Modified TTL invalidates checksum',bad.hex())]
# Define the reusable operation subnet; keep its logic separate from the trial.
def subnet():
n=ipaddress.ip_network('192.0.2.73/26',strict=False)
return [check(str(n.network_address)=='192.0.2.64' and str(n.broadcast_address)=='192.0.2.127' and len(list(n.hosts()))==62,'CIDR /26',str(n)),check(len(list(ipaddress.ip_network('192.0.2.72/31').hosts()))==2,'Point-to-point /31','2 addresses')]
# Define the reusable operation dns; keep its logic separate from the trial.
def dns():
def query(name):return bytes.fromhex('123401000001000000000000')+b''.join(bytes([len(x)])+x.encode() for x in name.split('.'))+b'\0\0\1\0\1'
def respond(q):
found=q==query('sensor.example');return q[:2]+struct.pack('!5H',0x8500 if found else 0x8503,1,int(found),0,0)+q[12:]+(bytes.fromhex('c00c000100010000003c0004c000020a') if found else b'')
q=query('sensor.example');r=exchange(q,respond); n=exchange(query('unknown.example'),respond)
out=[check(r[:2]==q[:2] and r[3]&15==0 and r[6:8]==b'\0\1' and r[-4:]==bytes([192,0,2,10]),'DNS-format UDP positive response',r.hex()),check(n[3]&15==3 and n[6:8]==b'\0\0','DNS-format NXDOMAIN',n.hex())]
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
body=b'{"temperature":25}' if self.path=='/temp' else b'Not found'; self.send_response(200 if self.path=='/temp' else 404);self.send_header('Content-Length',str(len(body)));self.end_headers();self.wfile.write(body)
def log_message(self,*a):pass
with HTTPServer(('127.0.0.1',0),Handler) as s:
thread=threading.Thread(target=s.serve_forever,daemon=True);thread.start()
try:
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}));url='http://127.0.0.1:'+str(s.server_port)
with opener.open(url+'/temp',timeout=2) as res:out.append(check(res.status==200 and json.load(res)=={'temperature':25},'Actual HTTP GET','200 and JSON body'))
try:opener.open(url+'/missing',timeout=2)
except urllib.error.HTTPError as e:out.append(check(e.code==404,'Actual HTTP missing resource','404'))
else:raise AssertionError('Expected HTTP 404')
finally:s.shutdown();thread.join(timeout=2)
return out
# Define the reusable operation coap; keep its logic separate from the trial.
def coap():
con=bytes.fromhex('41011234abb474656d70');non=bytes.fromhex('51011234abb474656d70')
def respond(q):
if q==con:return bytes.fromhex('61451234abff3235')
if q==non:return bytes.fromhex('51455678abff3235')
raise AssertionError('unexpected fixture request')
r=exchange(con,respond);n=exchange(non,respond)
return [check(r==bytes.fromhex('61451234abff3235'),'Actual CoAP-format CON UDP exchange',r.hex()),check(n==bytes.fromhex('51455678abff3235'),'Actual CoAP-format NON UDP exchange',n.hex()),check(exchange(con,lambda _:None) is None,'Controlled dropped request; no response generated','fixture drop (not a measured timeout)'),check(exchange(con,respond)==r,'Repeated CON fixture recovery',r.hex())]
# Define the reusable operation ipv6; keep its logic separate from the trial.
def ipv6():
return [check(ipaddress.ip_address('2001:db8::1').compressed=='2001:db8::1','IPv6 address parsing','2001:db8::1'),check(exchange(b'IPv6',lambda q:q,socket.AF_INET6)==b'IPv6','Actual IPv6 UDP loopback','::1')]