Search code examples
pythonpython-3.xsocketsparsingtcpclient

Python 3: Parse Server message(TCP)


I wrote a client using the socket module and now I am trying to decode a message I receive from an external TCP Server with the following Code(I know the Package has an 8 byte long header with details such as size in the first 2 bytes. After the Header there is an error message, which I am trying to decode):

received = sock.recv(1024)
print ("Bytes Received: {}".format(received.decode()))

When doing this I get the following error message: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xdc in position 0: invalid continuation byte

When I try to exclude the header by using:

print ("Bytes Received: {}".format(received[9:].decode()))

I just get an empty result:

Bytes Received: 

Solution

  • Maybe you're trying to decode a '\x00' byte, for example:

    >>> print('Output: ' + b'\x00'.decode())
    Output: 
    >>> 
    

    Anyway, if it is long 8 bytes (UDP header is formed by 8 bytes, not TCP) you should write:

    print ("Bytes Received: {}".format(received[8:].decode()))
    

    If you want to work with TCP packets i suggest you to use a packet manipulator like Scapy: https://scapy.readthedocs.io/en/latest/installation.html