Skip to content

Instantly share code, notes, and snippets.

@yitsushi
Last active October 11, 2021 15:13
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 yitsushi/f28a50933d9059f65d33fd138a6fbd55 to your computer and use it in GitHub Desktop.
Save yitsushi/f28a50933d9059f65d33fd138a6fbd55 to your computer and use it in GitHub Desktop.
Quick python script to monitor DHCP traffic
#!/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()
@yitsushi
Copy link
Author

yitsushi commented Oct 11, 2021

❯ sudo NET_DEVICE=virbr0 ./listen.py
<52:54:00:bb:d4:b8 | 99:f0:69:10:5b:c3:cf:cc> Release
<52:54:00:bb:d4:b8 | 99:f0:69:10:5b:c3:cf:cc> Discover -> for xxxxxxxxx
<52:54:00:bb:d4:b8 | 00:00:00:00:00:00:00:00> Offer -> 192.168.122.99
<52:54:00:bb:d4:b8 | 99:f0:69:10:5b:c3:cf:cc> Request -> xxxxxxxxx = 192.168.122.99
<52:54:00:bb:d4:b8 | 00:00:00:00:00:00:00:00> Ack -> xxxxxxxxx

To listen on all devices: NET_DEVICE=any

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment