Friday, 04 March 2016 17:44

Python to Extract DHCP IP Request and Client Mac Address

Written by 
Rate this item
(0 votes)

Python script to parse DHCP handshakes and extract requested IP address and client Mac address


In DHCP Filters using TCPDump to extract IP and Mac Address, we used multple piped outputs of TCPDump, grep, and awk to produce the client mac address along with the requested ip address from a DHCP handshake.  This is good for just running in a console to produce the data needed in real time, but I want to do more with the data and print past and most recent ip's, client mac addresses and other relavent information onto an LCD screen attached to my Raspberry Pi.  I will use python to do the processing and printing.


Python Code to parse IP and Mac Address

To replicate a similar output of the command

sudo tcpdump -l -s 0 -ni wlan0 -vvv '((udp port 67) and (udp[8:1] = 0x1))' | grep --line-buffered -E -i 'requested-ip|client-id' | awk '{print $NF}'

In python we can do something like this

    Parses output of TCPDump with capture filters to print requested IP and client mac address
    Algis Salys

import subprocess as sub
import re

def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search

p = sub.Popen(('sudo', 'tcpdump', '-l', '-s 0', '-vvv', '-n', '((udp port 67) and (udp[8:1] = 0x1))'), stdout=sub.PIPE)
for row in iter(p.stdout.readline, b''):
    if findWholeWord('requested-ip')(row):
        print row.split(' ')[-1]
    elif findWholeWord('client-id')(row):
        print row.split(' ')[-1]











Read 5451 times Last modified on Saturday, 05 March 2016 18:17
Algis Salys

Creator and owner of  Linux enthusiast, electronics tinkerer, and likes to spend time in the workshop building and creating new projects.