0

I've tried encode() and it doesn't work. I keep getting TypeError: must be str, not bytes because normally I'd get TypeError: a bytes-like object is required, not 'str'.

ip = socket.gethostbyname("google.com")
port = 80
robot = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
payload = "Hello world"
try:
    robot.connect((ip, port)))
    robot.send('GET '+payload.encode()+' HTTP/1.1\n\n')
except socket.error:
    print("connection lost")
robot.close()

I dont understand what I did wrong?

1 Answer 1

3

If you look at the documentation for socket.send, you can see that the first argument is bytes, not a string. You encode a string with a particular encoding to turn it into bytes, and you decode bytes with a particular encoding to turn them into a string:

robot.send(b'GET ' + payload.encode() + b' HTTP/1.1\n\n')

str.encode and str.decode default to utf-8.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.