简体   繁体   中英

Problem with sockets on Black Hat Python code book

I've trying to follow this book's code, but is written in python 2. At first, I tried to run the book's code:

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))

msg = "Hi!"

"""MSG = msg.encode()"""
client.send(msg)

response = client.recv(4096)

print(response)

Then it run into this error: TypeError: a bytes-like object is required, not 'str'. Which I corrected with some encoding like this:

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))

msg = "Hi!"
MSG = msg.encode()
client.send(MSG)

response = client.recv(4096)

print(response)

But now, the code doesn't print anything. What can be wrong?

The book's code is send "GET / HTTP/1.1\\Host: google.com\\r\\n\\r\\n". This code means send a get request to google, so it can get response for request you sent . Your msg is not a HTTP's request, so google will not send response for you msg.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM