Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Python by (47.6k points)

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.

1 Answer

0 votes
by (106k points)
edited by

You can get rid of the error by using the below-mentioned way:-

And the reason you are getting that error is in Python 3, strings are Unicode, but when transmitting on the network, the data needs to be bytes strings instead. So... a couple of suggestions:

  1. The first thing you can use is c.sendall() method instead of c.send() to prevent possible issues where you may not have sent the entire msg with one call.

  2. For literals, add a 'b' for bytes string: c.sendall(b'Thank you for connecting')

  3. For variables, you need to encode Unicode strings to byte strings (see below)

Below is the code which will work both on Python 2.0 as well as Python 3.0:-

output = 'Thank you for connecting'

c.sendall(output.encode('utf-8'))

To know more about this you can have a look at the following video tutorial:-

To Learn what is python and python applications then visit this Data Science with Python.

Wanna become an Expert in python? Come & join our Python Certification course

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...