문제

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 !

도움이 되었습니까?

해결책

You could use:

  • ctypes which is part of the standard library, or
  • Construct which is designed to support network protocols,
  • bitarray which isn't,
  • bitstring which 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)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top