Scapy: how do I get the full IP packet header?

Ricky Robinson picture Ricky Robinson · Aug 3, 2012 · Viewed 8k times · Source

In Scapy, I want to manually match packets with their corresponding ICMP time-exceeded messages.

I need to match:

  • IP-in-ICMP field of ICMP packet
  • IP header and first 8 bytes of my data packet The ICMP packet isn't a problem:

    icmpPayload = str(icmpPacket[ICMP].payload)

As for the first 8 bytes of the data packet, I just need to do:

str(myPacket[IP].payload)[:8]

I don't know how to get only the IP header of myPacket. All I do now is replace the payload in the whole packet with its first 8 bytes. This search and replace, if applied to thousands of packets, might take too long, I'm afraid:

 strOfMyPacket = str(myPacket[IP])
 strOfMyPacket.replace(str(myPacket[IP].payload),str(myPacket[IP].payload)[:8],1)

Any faster way that will let me do simply the following?

 partOfPayload = str(myPacket[IP].payload)[:8]
 fullHeader = _______
 stringToCompare = fullHeader + partOfPayload

Answer

tMC picture tMC · Aug 24, 2012
str(myPacket)[:(myPacket[IP].ihl * 4)]

The IP header length is in the field ihl (Internet Header Length). It is represented as the number of 32bit words the header uses. (it is variable because of the 'options' section of the header). So, if we multiply that field by 32 and then divide by 8 (or * 4) we get the number of bytes the header fills, whether is has options or not.

I am surprised there is no method (that i could find) to return JUST the IP header without the lower layers.

http://en.wikipedia.org/wiki/IPv4_header#Header