Sending DHCP Discover with Python and Scapy

Simple example how to send a UDP packet with Scapy in a Python application:

import random

from scapy.all import Ether, IP, UDP, BOOTP, DHCP, sendp

def mac_to_bytes(mac_addr: str) -> bytes:
    """ Converts a MAC address string to bytes.
    return int(mac_addr.replace(":", ""), 16).to_bytes(6, "big")

client_mac = "01:02:03:04:05:06"
packet = (
    Ether(dst="ff:ff:ff:ff:ff:ff") /
    IP(src="", dst="") /
    UDP(sport=68, dport=67) /
        xid=random.randint(1, 2**32-1),
    ) /
    DHCP(options=[("message-type", "discover"), "end"])
sendp(packet, iface="ens192", verbose=False)

When using sendp() it is necessary to construct the full packet, starting from L2 Ethernet frame.

The "/" operator is cleverly used when combining the layers of the packet.

Leave a Reply