Python TypeError socket error: a byte-like object is needed, not a 'str' with a send function

I am trying to create a program that will open a port on a local computer and allow others to connect to it via netcat. My current code.

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 using the command:

 nc 127.0.0.1 12345 

But then in my Python script, I get an error for c.send:

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

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

+14
source share
3 answers

The reason for this error is that in Python 3, strings are Unicode, but when transmitted over a network, the data must be byte strings. So ... a couple of suggestions:

  1. Suggest using c.sendall() instead of c.send() to prevent possible problems when you may not have sent all the messages in one call (see the Documentation ).
  2. For literals, add the string 'b' for bytes: c.sendall(b'Thank you for connecting')
  3. For variables, you need to encode Unicode strings into byte strings (see below)

Best solution (should work with 2.x and 3.x):

 output = 'Thank you for connecting' c.sendall(output.encode('utf-8')) 

Epilogue / History: This is not a problem in Python 2 because strings are already byte strings - your OP code will work fine in this environment. Unicode strings were added in Python in releases 1.6 and 2.0, but remained in the background until 3.0 when they became the default string type. Also see this similar question, as well as this one .

+35
source

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

+6
source

You can change the send string to this:

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

b does it bytes instead.

+3
source

Source: https://habr.com/ru/post/1265064/


All Articles