问题
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
回答1:
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
回答2:
In case someone else bumps into this question, I think you may be able to use remove_payload() function of class Packet(inherited by IP). This should just leave the header. I am new to scapy but it looks like it works when i tried it on the interpreter.
>>> ip = IP(dst='10.0.0.1', src='10.0.0.14', ttl=255)/ICMP()
>>> hexdump(ip)
0000 45 00 00 1C 00 01 00 00 FF 01 A7 D1 0A 00 00 0E E...............
0010 0A 00 00 01 **08 00 F7 FF 00 00 00 00** ............
>>> ip.remove_payload()
>>> hexdump(ip)
0000 45 00 00 14 00 01 00 00 FF 00 A7 DA 0A 00 00 0E E...............
0010 0A 00 00 01 ....
>>>
来源:https://stackoverflow.com/questions/11794602/scapy-how-do-i-get-the-full-ip-packet-header