connect python 3x to a server

Asked

Viewed 141 times

5

I have been studying python for some time and I was trying to create a script to connect to a server and get a response from it, but when I use the code I get an error that I can’t fix

My code

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

#criar um objeto socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#conectar o cliente
client.connect((target_host,target_port))

#envia alguma dados
client.send('GET / HTTP/1.1\R\NHost: google.com\r\n\r\n')

#recebe dados
response = client.recv(4096)

print(response)

The mistake is:

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

Can someone help me?

2 answers

3


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

#criar um objeto socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#conectar o cliente
client.connect((target_host,target_port))

#envia alguma dados
client.send('GET / HTTP/1.1\R\NHost: google.com\r\n\r\n'.encode())

#recebe dados
response = client.recv(4096)

print(response)

You need to use .encode() send requires bytes, not a string

  • Is this what I’m supposed to get in response? b'HTTP/1.0 400 Bad Request r nContent-Length: 54 r nContent-Type: text/html; charset=UTF-8 r nDate: Wed, 01 May 2019 10:30:05 GMT r n r r n<html><title>Error 400 (Bad Request)!! 1</title></html>'

  • I believe so, since it was a missing requisition

2

You can make a conversion in your send() for the guy bytes before making the request. I read in the English forum that they also recommend the use of sendall() to prevent future problems.

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

#criar um objeto socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#conectar o cliente
client.connect((target_host,target_port))

#envia alguma dados
client.sendall(b'GET / HTTP/1.1\R\NHost: google.com\r\n\r\n')

#recebe dados
response = client.recv(4096)

print(response)
  • b'HTTP/1.0 400 Bad Request r nContent-Length: 54 r nContent-Type: text/html; charset=UTF-8 r nDate: Wed, 01 May 2019 10:30:05 GMT r n r r r n<html><title>Error 400 (Bad Request)!! 1</title></html>' I’m supposed to get this answer?

  • I believe so, because you completed the request successfully but the server that you executed the action returned a 'Bad request', that is, this request could not be answered. See more information about bad request

Browser other questions tagged

You are not signed in. Login or sign up in order to post.