trying to create packet sniffer using raw socket in python, and want to parse the full TCP header using struct.unpack method, but some fields like HLEN(4bits) and offset, URG,ACK,PST,RST,SYN,FIN in tcp header are on bits not Byte . so my question is how to parse these values from header !
1 Answers
0
votes
You could use:
ctypeswhich is part of the standard library, orConstructwhich is designed to support network protocols,bitarraywhich isn't,bitstringwhich isn't as well.
Here is an example:
from ctypes import c_int32, c_uint32, Structure, Union
class _bits(Structure):
_fields_ = [
("odd", c_uint32, 1),
("half", c_uint32, 31),
]
class Int(Union):
_fields_ = [
("bits", _bits),
("number", c_uint32),
]
a = Int(number=12345)
a.bits.odd, a.bits.half
the result:
>>> a = Int(number=12345)
>>> a.bits.odd, a.bits.half
(1L, 6172L)