4

Im reading data from an tcp connection. If I read the data from wireshark(network monitor) I get 02501c41d11ec06a471102 but if I read data in python i get it in bytes:

b'\x02P\x1cA\xd1\x1e\xc0jG\x11\x02'
<class 'bytes'>

How do I convert this? I tried this:

#!/usr/bin/env python

import socket
import binascii
import time
import sys

TCP_IP = '10.20.0.195'
TCP_PORT = 9761
BUFFER_SIZE = 2048

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))

while 1:
    data = s.recv(1024)
    print (data)
    data2 = data.decode("utf-8")
    typ = type(data)
    print (typ)

but if in run this I get:

b'\x02P\x1cA\xd1\x00\x00\x02\xcb\x11\x00'
Traceback (most recent call last):
  File "Z:/programeren/domotica/try again/receive.py", line 18, in <module>
    data2 = data.decode("utf-8")
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd1 in position 4: invalid continuation byte

just to be clear i want to turn

b'\x02P\x1cA\xd1\x00\x00\x02\xcb\x11\x00'

into

02501c41d11ec06a471102
1
  • You're starting with bytes. .decode('utf-8') means decode from UTF-8 to a unicode string. Also, it seems like both those strings are same-ish, the Wireshark one is just all formatted as hexadecimals, and the Python one has a mixture of \x escapes and printable characters. Commented Aug 4, 2013 at 12:12

1 Answer 1

4

Use binascii.b2a_hex (or binascii.hexlify).

>>> import binascii
>>> binascii.b2a_hex(b'\x02P\x1cA\xd1\x00\x00\x02\xcb\x11\x00')
b'02501c41d1000002cb1100'
>>> binascii.b2a_hex(b'\x02P\x1cA\xd1\x00\x00\x02\xcb\x11\x00').decode('ascii')
'02501c41d1000002cb1100'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.