Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am using the below script to make request to google. However, when I execute it, I get the error stating:

client.send("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n") TypeError: a bytes-like object is required, not 'str'

On browsing for similar issues in stackoverflow, client.sendto has been recommended to use along with encoding the message. However, in my case there is no message that is passed.

The below is the script I use:

import socket
target_host = "www.google.com"
target_port = 80

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((target_host,target_port))
client.send("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n")
response = client.recv(4096)
print(response)

Any pointers on correcting the issue will be appreciated.

like image 608
mbvee Avatar asked Oct 22 '25 17:10

mbvee


1 Answers

You need to choose an encoding, example:

client.send("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n".encode(encoding='utf-8'))

See also: Python Socket Send Buffer Vs. Str and TypeError: 'str' does not support the buffer interface

like image 104
Luca Citi Avatar answered Oct 25 '25 06:10

Luca Citi