Sending binary data over sockets with Python

后端 未结 2 1423
忘掉有多难
忘掉有多难 2020-12-31 05:20

I\'m looking to script some basic requests over the SPDY protocol. The protocol defines the frames you send as being comprised of binary data of very specific length and byt

2条回答
  •  情书的邮戳
    2020-12-31 06:06

    You can also use the struct module to define the header format with a string and parse it directly.

    To generate a packet:

    fmt = 'B I 4b'
    your_binary_data = pack(fmt, header_data)
    sock.sendall(your_binary_data)
    

    Where fmt indicates the header format ('B I 4b' is just a, clearly not working for your SPDY header, example). Unfortunately, you will have to deal with non-byte-alligned header fields, probably by parsing bigger chunks and then dividing them according to your format.

    Aside that, to parse the header:

    unpacker = struct.Struct('B I 4b')
    unpacked_data = unpacker.unpack(s.recv(unpacker.size))
    

    unpacked_data will contain a tuple with the parsed data.

    The struct module performs conversions between Python values and C structs represented as Python strings. I have no guarantees about the efficiency of this approach, but it helped me to parse different protocols just by adjusting the fmt string.

提交回复
热议问题