Skip to content

Instantly share code, notes, and snippets.

@itdaniher
Created April 4, 2018 20:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itdaniher/d3f18431627dce58640dadbcc2d2bea8 to your computer and use it in GitHub Desktop.
Save itdaniher/d3f18431627dce58640dadbcc2d2bea8 to your computer and use it in GitHub Desktop.
tiny_dhcp.py
from threading import Thread
from scapy.layers.inet import Ether, IP, UDP
from scapy.layers.dhcp import DHCP, BOOTP
from scapy.config import conf
from scapy.arch import get_if_raw_hwaddr, get_if_hwaddr
from scapy.sendrecv import sniff, sendp
import queue
import time
BOOTREPLY = 2
def dhcp_reqresp(interface="wwan0", timeout=5):
q = queue.Queue()
conf.checkIPaddr=False
BOOTREPLY = 2
_, rawmacaddress = get_if_raw_hwaddr(interface)
macaddress= get_if_hwaddr(interface)
def listen():
sniff(filter="udp and (port 67 or port 68)", prn=lambda pkt: q.put(pkt), store=0, count=2, timeout=timeout, iface=interface)
def start_listener():
thread = Thread(target=listen)
thread.start()
return thread
listener_thread = start_listener()
time.sleep(1.0)
discover = Ether(dst='ff:ff:ff:ff:ff:ff', src=macaddress, type=0x0800) / IP(src='0.0.0.0', dst='255.255.255.255') / UDP(dport=67,sport=68) / BOOTP(op=1, chaddr=rawmacaddress) / DHCP(options=[('message-type','discover'), ('end')])
sendp(discover, iface=interface, verbose=False)
try:
req = q.get(timeout=timeout//2)
rsp = q.get(timeout=timeout//2)
except queue.Empty:
return None
if rsp[BOOTP]:
if rsp[BOOTP].op == BOOTREPLY:
client = rsp[BOOTP].yiaddr
server = rsp[BOOTP].siaddr
return rsp, client, server
rsp.display()
if __name__ == "__main__":
import sys
results = dhcp_reqresp(interface=sys.argv[1])
if results and len(results) == 3:
results[0].display()
print(results[1], results[2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment