Dancer PhD
Dancer PhD

Reputation: 307

Python socket data parsing TypeError: Can't convert 'bytes' object to str implicitly

Below is the fragment of the code which I found for parsing data from the package. I get above error when I run the code. Can someone please explain the reason for this. This is small network sniffing program scenery. Thank you for reading

if protocol == 6 :
        t = iph_length + eth_length
        tcp_header = packet[t:t+20] 
        tcph = unpack('!HHLLBBHHH' , tcp_header)
        source_port = tcph[0]
        dest_port = tcph[1]
        sequence = tcph[2]
        acknowledgement = tcph[3]
        doff_reserved = tcph[4]
        tcph_length = doff_reserved >> 4

        print ('Source Port : ' + str(source_port) + ' Dest Port : ' + str(dest_port) + ' Sequence Number : ' + str(sequence) + ' Acknowledgement : ' + str(acknowledgement) + ' TCP header length : ' + str(tcph_length))

        h_size = eth_length + iph_length + tcph_length * 4
        data_size = len(packet) - h_size

        #get data from the packet
        data = packet[h_size:]

        print ('Data : ' + data)

Upvotes: 0

Views: 152

Answers (1)

Sandeep Lade
Sandeep Lade

Reputation: 1943

Seems you are using bytes object as string in your code. Before using it as a string you use <bytesobject>.decode("utf-8") to decode

 >>> b"abcde".decode("utf-8")
    u'abcde'
   >>> b"slade".decode("utf-8")
    u'slade'
    >>> 

If you are facing issues use below code

b'Z\t.\xf0\xdd\xbb\x84\xb5\x9c\xf9\x080\x08\x00E\x00\x004\xa‌​7\xe6\x00\x000\x06\x‌​1ax\x98B\xf8\xb5h\xe‌​c\xce\x81\xf0\x92\x0‌​0\x16\xd4}\x9fd\x18\‌​xe8y\x94\x80\x10\x7f‌​\xfe*\xfa\x00\x00\x0‌​1\x01\x08\nT\xb2\xa9‌​ZC\xdb\xcan'.decode(‌​"utf-8", "ignore")

Upvotes: 1

Related Questions