Search code examples
pythonscapy

Scapy - How to simulate IP Header/Packet with size less than minimum (20 bytes)


Can someone help me out, how to simulate IP packet with size smaller than minimum using scapy.

I wanted to reduce the size to 10 to validate an error counter.

Snip from scapy

>>> i=IP(src="20.1.1.2",dst="20.1.1.1")

>>> len(i)
20 

I need to reduce this value


Solution

  • Scapy won't let you change the number of bytes in the IP header. What you can do instead is load the raw IP bytes as data on top of the eth payload.

    Create the packet

    Here we load the IP header as bytes.

    >>> ip_data=IP(src="20.1.1.2",dst="20.1.1.1")
    >>> raw(ip_data)
    b'E\x00\x00\x14\x00\x01\x00\x00@\x00P\xe5\x14\x01\x01\x02\x14\x01\x01\x01'
    >>> packet = Ether()/raw(ip_data)
    

    Inspect the packet bytes

    We can look at the raw bytes in the packet as an array to look at only the first 10 (or all of the) bytes of the IP header "payload":

    >>> packet_bytes = raw(packet)
    WARNING: Mac address to reach destination not found. Using broadcast.
    >>> eth_boundary = 14
    >>> packet_bytes[eth_boundary:]    # All IP bytes
    b'E\x00\x00\x14\x00\x01\x00\x00@\x00P\xe5\x14\x01\x01\x02\x14\x01\x01\x01'
    >>> packet_bytes[eth_boundary:eth_boundary+10]  # Only first 10 bytes
    b'E\x00\x00\x14\x00\x01\x00\x00@\x00'