3

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.

mbvee
  • 383
  • 2
  • 4
  • 16
  • What do you mean "there is no message"? You are clearly sending an HTTP request. – Pedro Castilho Apr 05 '17 at 17:30
  • 1
    In Python 3, `""GET / HTTP/1.1\r\nHost: google.com\r\n\r\n"` is a unicode string and `.send()` wants bytes to send over the wire. Your code tries to send the unicode string straight without encoding, which the error message rightfully complains about. – dhke Apr 05 '17 at 17:36

1 Answers1

6

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

Community
  • 1
  • 1
Luca Citi
  • 1,310
  • 9
  • 9