PYTHON · Code cell
# =====================================================================
# N05 | Code cell 02 | DNS & HTTP application services
# 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.
# =====================================================================
import 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 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