Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TCP Receive in Python, reading the data out

My Python script is as below (sensitive data removed where necessary)

import socket

class TCPConnection:
    def __init__(self, sock=None):
        if sock is None:
            self.sock = socket.socket(
                            socket.AF_INET, socket.SOCK_STREAM)
        else:
            self.sock = sock

    def connect(self, host, port):
        try:
            self.sock.connect((host, port))
            print('Successful Connection')
        except:
            print('Connection Failed')

    def readlines(self):
        data = self.sock.recv(1024)
        print(data)


if __name__ == '__main__' : 
    listen = TCPConnection()
    listen.connect('**.**.**.**',##)
    listen.readlines()

I'm getting the following output.

Successful Connection
b'\x01\x00\xc7\x00\x08\x01\x07\t\x00\x00\x00\x03='

What do I now need to do to make the printed output from the readlines() function more friendly? From the look of it, I know it's in bytes, but beyond that, I'm lost.

All help is gracefully received.

like image 901
oliversarfas Avatar asked Apr 10 '26 09:04

oliversarfas


1 Answers

You can decode the message before printing it:

def readlines(self):
    data = self.sock.recv(1024).decode()
    print(data)

but still please consider that your data is not "ASCII" or "UTF-8".

like image 103
Gabriel Ciubotaru Avatar answered Apr 11 '26 23:04

Gabriel Ciubotaru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!