Pregunta

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 !

¿Fue útil?

Solución

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)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top