def gethostbyname(hostname, timeout=5): sock = udp.socket() try: for sip in servers: ident = random.getrandbits(16) sock.sendto((sip, 53), mkquery(ident, hostname)) res = sock.recv(timeout=timeout) if res is None: continue res = Response.decode(res) if res is None: continue #if res.ident != ident: # continue if res.QR != Qr.R: continue if res.rcode != RCode.NOERR: continue # only look at the answers reccord, skip auth/extra RRs # TODO: alias for r in res.QRs[1]: if r.typ == RRT.A and r.cls == RRC.IN: _cache.setdefault(hostname, []).append(ip4(r.data)) finally: sock.close() if hostname in _cache: return _cache[hostname][0] return None
def run(self): sock = udp.socket() sock.bind((0, self.PORT)) while True: cli = sock.recvfrom() if not cli: break sock.sendto(cli[0], ('%s\r\n' % datetime.datetime.today()).encode()) log.info('[daytime]: server stopped')
from rdt import rdt_server from threading import Timer import time import sys import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S') SERVER_ADDR = '127.0.0.1' SERVER_PORT = 12000 ACK_NUM = 0 if __name__ == "__main__": server = socket() server.bind((SERVER_ADDR, SERVER_PORT)) receiver = rdt_server(server, SERVER_ADDR, SERVER_PORT, ACK_NUM) logging.info("Wait for receiving from the client ...") start_time = time.time() end_time = time.time() while True: end_time = time.time() if abs(end_time - start_time) >60: logging.info("Server close") sys.exit() try: recv_packet, receiver.client_addr_port = server.recvfrom(4096) start_time = time.time() recv_payload = receiver.rdt_unpack(recv_packet) logging.info("Server receives packet {}".format(int.from_bytes(recv_payload.SEQ, 'big')))
def traceroute(host, *, sport=None, nhop=20, nprobes=3, timeout=5): '''Trace route using UDP''' dip = ip4(host) dport = 33333 if sport is None: sport = (os.getpid() & 0xffff) | 0x8000 pktlen = 60 datalen = pktlen - 20 - 8 assert datalen >= len(marshal.dumps((int(), float()))) sendsock = udp.socket().bind((0, sport)) recvsock = raw.socket(ipv4.IPPROT.ICMP) print('traceroute to %s, %d hops max, %d bytes packets' % (dip, nhop, pktlen), flush=True) try: seq = 0 for ttl in range(1, nhop+1): sendsock.setsockopt(DF=1, ttl=ttl) print('%2d' % ttl, end='', flush=True) done = 0 lastsip = None for probe in range(1, nprobes+1): sendtime = time.time() seq += 1 sendsock.sendto((dip, dport+seq), marshal.dumps((ttl, sendtime)).ljust(datalen, b'\x00')) ret = None while True: now = time.time() wait = timeout - (now - sendtime) if wait <= 0: ret = None break ret = recvsock.recvfrom(timeout=wait) if not ret: break (sip, ippkt) = ret icmppkt = icmp.decode(ippkt.pdu) if ((icmppkt.type == icmp.ICMP_TIMXCEED and icmppkt.code == icmp.TIMXCEED_INTRANS) or icmppkt.type == icmp.ICMP_UNREACH): try: ippkt2 = ipv4.decode(icmppkt.data) except DecodeError as e: print(e, file=sys.stderr, flush=True) continue if ippkt2.proto != ipv4.IPPROT.UDP: continue udppkt = udp.decode(ippkt2.pdu) if (udppkt.sport == sport and udppkt.dport == dport + seq): ret = (sip, icmppkt) break if not ret: print('\t*', end='', flush=True) continue rtt = (time.time() - sendtime) * 1000 sip, icmppkt = ret if sip != lastsip: print('\t%s %7.3f ms' % (sip, rtt), end='', flush=True) lastsip = sip else: print('\t%7.3f ms' % rtt, end='', flush=True) if sip == dip: done += 1 print(flush=True) if done: break finally: sendsock.close() recvsock.close() return True
format= '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S') SERVER_ADDR = '127.0.0.1' SERVER_PORT = 12000 WINDOW_BASE = 0 WINDOW_SIZE = 5 TIME_OUT = 1 PAYLOAD_SIZE = 1024 with open('./alice.txt', 'rb') as f: MESSAGE = f.read() if __name__ == "__main__": client = socket() sender = rdt_client(client, SERVER_ADDR, SERVER_PORT, WINDOW_BASE, WINDOW_SIZE, WINDOW_BASE, TIME_OUT, PAYLOAD_SIZE) file = open('./alice.txt', 'rb') recv_file = open('./recv_file.txt', 'wb') while True: while True: try: if sender.next_seq < sender.window_base + sender.window_size: message = file.read(sender.payload_size) logging.info("Read file into message") if not message: logging.info("File read completed") sender.end = sender.next_seq - 1 break
def boot(hint_ip=None, timeout=5): sock = udp.socket().bind((0, 68)) try: return _boot(sock, hint_ip, timeout) finally: sock.close()