DDDD
DDDD

Reputation: 153

Python3 socket client to send and receive hex string

I am stuck in this socket client Python3 code:

import socket
import codecs

def Main():
        host = '127.0.0.2'
        port = 502

        mySocket = socket.socket()
        mySocket.connect((host,port))

        message = codecs.encode('\x00\x00\x00\x00\x00\x06\x01\x04\x00\x01\x00\x02')

        mySocket.send(message)
        data = codecs.decode(mySocket.recv(1024))

        print ('Received from server: ' + data)


        mySocket.close()

if __name__ == '__main__':
    Main()

It gives the error

File "C:\Python34\lib\encodings\utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb3 in position 11: invalid start byte

I am trying to connect to a Ananas - Modbus/TCP -server

What is the error?

Thanks!

Upvotes: 2

Views: 8004

Answers (1)

Pirheas
Pirheas

Reputation: 332

It's because it try to convert data into an utf-8 string (and some of the bytes contained are not possible to represent in utf-8).

If you want to see the hexadecial value of a byte array you can:

Python3.5+

data = mySocket.recv(1024)
data.hex()

Othewrise

>>> import binascii
>>> data = mySocket.recv(1024)
>>> data = binascii.hexlify(data).decode()

Upvotes: 5

Related Questions