You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dhcp_client.py 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. from dhcp_packet import *
  2. import socket
  3. import random
  4. from type_hwmac import *
  5. import pcap
  6. import dpkt
  7. import binascii
  8. import time
  9. class DhcpClient:
  10. def send_packet(self, mac, iface, xid):
  11. dhcp = DhcpPacket()
  12. dhcp.SetOption('op', [1])
  13. dhcp.SetOption('htype', [1])
  14. dhcp.SetOption('hlen', [6])
  15. dhcp.SetOption('xid', xid)
  16. dhcp.SetOption('chaddr', hwmac(mac).list())
  17. dhcp.SetOption('dhcp_message_type', [1])
  18. dhcp.SetOption('parameter_request_list', [12])
  19. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  20. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  21. s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
  22. s.setsockopt(socket.SOL_SOCKET, 25, iface + '\0')
  23. s.bind(('', 68))
  24. s.sendto(dhcp.EncodePacket(), ('255.255.255.255', 67))
  25. s.close()
  26. def get_offer(self, mac, iface, timeout = 10):
  27. pc = pcap.pcap(name=iface)
  28. pc.setfilter('udp and udp src port 67 and udp dst port 68')
  29. xid = [random.randrange(255), random.randrange(255),
  30. random.randrange(255), random.randrange(255)]
  31. self.send_packet(mac, iface, xid)
  32. pc.setnonblock()
  33. start = time.time()
  34. while True:
  35. try:
  36. for pkt in pc.readpkts():
  37. eth = dpkt.ethernet.Ethernet(pkt[1])
  38. dh = DhcpPacket()
  39. dh.DecodePacket(eth.data.data.data)
  40. if (dh.GetOption('xid') == xid and
  41. dh.GetOption('op') == [2] and
  42. dh.GetOption('dhcp_message_type') == [2]):
  43. return dh
  44. except:
  45. pass
  46. time.sleep(0.5)
  47. if time.time() - start >= timeout:
  48. return None