from dhcp_packet import * import socket import random from type_hwmac import * import pcap import dpkt import binascii import time class DhcpClient: def send_packet(self, mac, iface, xid): dhcp = DhcpPacket() dhcp.SetOption('op', [1]) dhcp.SetOption('htype', [1]) dhcp.SetOption('hlen', [6]) dhcp.SetOption('xid', xid) dhcp.SetOption('chaddr', hwmac(mac).list()) dhcp.SetOption('dhcp_message_type', [1]) dhcp.SetOption('parameter_request_list', [12]) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.setsockopt(socket.SOL_SOCKET, 25, iface + '\0') s.bind(('', 68)) s.sendto(dhcp.EncodePacket(), ('255.255.255.255', 67)) s.close() def get_offer(self, mac, iface, timeout = 10): pc = pcap.pcap(name=iface) pc.setfilter('udp and udp src port 67 and udp dst port 68') xid = [random.randrange(255), random.randrange(255), random.randrange(255), random.randrange(255)] self.send_packet(mac, iface, xid) pc.setnonblock() start = time.time() while True: try: for pkt in pc.readpkts(): eth = dpkt.ethernet.Ethernet(pkt[1]) dh = DhcpPacket() dh.DecodePacket(eth.data.data.data) if (dh.GetOption('xid') == xid and dh.GetOption('op') == [2] and dh.GetOption('dhcp_message_type') == [2]): return dh except: pass time.sleep(0.5) if time.time() - start >= timeout: return None