Last active
October 11, 2021 15:13
-
-
Save yitsushi/f28a50933d9059f65d33fd138a6fbd55 to your computer and use it in GitHub Desktop.
Quick python script to monitor DHCP traffic
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import os | |
import pyshark | |
dhcp_ports = [ | |
67, 68, # dhcp | |
546, 547, # dhcpv6 | |
] | |
dhcp_types = { | |
1: "Discover", | |
2: "Offer", | |
3: "Request", | |
4: "Decline", | |
5: "Ack", | |
6: "Nak", | |
7: "Release", | |
} | |
cap = pyshark.LiveCapture(os.environ["NET_DEVICE"]) | |
for packet in cap.sniff_continuously(): | |
if packet.transport_layer != "UDP": | |
continue | |
if ( | |
int(packet.udp.dstport) not in dhcp_ports or | |
int(packet.udp.srcport) not in dhcp_ports | |
): | |
continue | |
dhcp = packet.dhcp | |
option = int(dhcp.option_value) | |
try: | |
client_id = dhcp.client_id | |
except Exception: | |
client_id = "00:00:00:00:00:00:00:00" | |
try: | |
hw_mac_addr = dhcp.hw_mac_addr | |
except Exception: | |
hw_mac_addr = "00:00:00:00:00:00" | |
try: | |
host = dhcp.option_hostname | |
except Exception: | |
host = "[unknown hostname]" | |
try: | |
yourip = dhcp.ip_your | |
except Exception: | |
yourip = "[unknown offered ip address]" | |
try: | |
requested = dhcp.option_requested_ip_address | |
except Exception: | |
requested = "[unknown requested ip address]" | |
if option in dhcp_types: | |
print(f"<{hw_mac_addr} | {client_id}> {dhcp_types[option]}", end="") | |
else: | |
print(f"<{hw_mac_addr} | {client_id}> {dhcp.option_type}::{dhcp.option_value}", end="") | |
if option == 1: | |
# Discover | |
print(f" -> for {host}") | |
elif option == 2: | |
# Offer | |
print(f" -> {yourip}") | |
elif option == 3: | |
# Request | |
print(f" -> {host} = {requested}") | |
elif option == 4: | |
# Decline | |
print() | |
elif option == 5: | |
# Ack | |
print(f" -> {host}") | |
elif option == 6: | |
# Nak | |
print() | |
elif option == 7: | |
# Release | |
print() | |
else: | |
print() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To listen on all devices:
NET_DEVICE=any