[python] Python sockets error TypeError: a bytes-like object is required, not 'str' with send function

I am trying to create a program that will open a port on the local machine and let others connect into it via netcat. My current code is.

s = socket.socket()
host = '127.0.0.1'
port = 12345
s.bind((host, port))

s.listen(5)
while True:
    c, addr = s.accept()
    print('Got connection from', addr)
    c.send('Thank you for connecting')
    c.close()

I am new to Python and sockets. But when I run this code it will allow me to send a netcat connection with the command:

nc 127.0.0.1 12345

But then on my Python script I get the error for the c.send:

TypeError: a bytes-like object is required, not 'str'

I am basically just trying to open a port, allow netcat to connect and have a full shell on that machine.

This question is related to python python-3.x

The answer is


You can decode it to str with receive.decode('utf_8').


You can change the send line to this:

c.send(b'Thank you for connecting')

The b makes it bytes instead.


An alternative solution is to introduce a method to the file instance that would do the explicit conversion.

import types

def _write_str(self, ascii_str):
    self.write(ascii_str.encode('ascii'))

source_file = open("myfile.bin", "wb")
source_file.write_str = types.MethodType(_write_str, source_file)

And then you can use it as source_file.write_str("Hello World").