Search code examples
pythonnetwork-programmingtcpscapy

How to read whole ip layer and tcp layer from a packet when using scapy?


I am doing a TCP retransmission behavior test when receiving ICMP Destination unreachable (Fragmentation needed ICMP TYPE=3 CODE=4) message with scapy.

The test flow like this:
1. Establish a TCP connection to the server
2. Send a HTTP GET request to the server when TCP is established
3. When HTTP Response back
4. Send an ICMP type 3 code 4 message to the server with s small MTU set

The question is that ICMP TYPE=3 CODE=4 message include the IP Header and partial TCP header (srt, dst and seq number) of that HTTP Response packets. Currently, I just read each paramemter (like IP identification, frag tag, ttl etc.) from that HTTP Response packets. The question is: is there any way that I can read the whole IP and TCP header from that packet:

ICMP(TYPE=3 CODE=4)/IP Header/TCP Header


Solution

  • Hopefully the following will help:

    >>> pkt = ICMP()/IP()/TCP()
    >>> ip_header = pkt.getlayer(IP) 
    >>> ip_header 
    <IP  frag=0 proto=tcp |<TCP  |>>
    >>> 
    

    To retrieve just the IP header:

    >>> pkt = Ether()/IP()/TCP()
    >>> ip = pkt.getlayer(IP)
    >>> ip
    <IP  frag=0 proto=tcp |<TCP  |>>
    >>> ip.remove_payload()
    >>> ip
    <IP  |>
    >>>