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.7KB

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