Search code examples
python-3.xtcpdump

why socket.recv() on python3 return value that lost the last byte?


So I have python code like this to send and receive UDP packet to a port

  s = socket(AF_INET, SOCK_DGRAM)
  UDP_IP = '1.0.0.45'
  UDP_PORT = 8100
  s.connect((UDP_IP, UDP_PORT))
  r = s.send(ethernet_packet + payload)
  data = s.recv(1024)
  print(data)

Packet sent successfully, in the tcpdump, the udp packet that i received is enter image description here

But the data that received is printed like this: b'\xff\xff\xff\xff\xff\xff\x00\x01\x00\x00\x00\x08\x80\x04\xc0\x00\x00\x00\x009' the last byte should be "x39", 3 is missing for some reason, does anyone know why? Thx in adv


Solution

  • This is expected behavior. If python can represent a byte in a bytes object as ASCII, it will. b'9' is just b'\x39', but python prefers ASCII for readability.

    >>> b"\x39"
    b'9'
    

    The Python docs for string literals indicate that ASCII characters and characters with hex values are valid in a bytes string.