The problem is that when I run this code for making simple client then I get error like this.
import socket
target_host = "www.google.com"
target_port = 80
# ➊ create a socket object
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# ➋ connect the client
client.connect((target_host,target_port))
# ➌ send some data
client.send("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n")
# ➍ receive some data
response = client.recv(4096)
print response
I first create a socket object with the AF_INET
and SOCK_STREAM
parameters ➊. The AF_INET
parameter is saying we are going to use a standard IPv4 address or host_name, and SOCK_STREAM
indicates that this will be a TCP client. We then connect the client to the server ➋ and send it some data ➌. The last step is to receive some data back and print out the response.
This Error occur when I run Traceback (most recent call last):
File "C:\Users\engin\Desktop\TCP_client.py", line 10, in <module>
client.send("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n")
TypeError: a bytes-like object is required, not 'str'
What is the problem?
You are trying to run Python2-Code with Python3, which would first result in a SyntaxError, because of the print-statement. Second, you have to send bytes, not strings:
client.send(b"GET / HTTP/1.1\r\nHost: google.com\r\n\r\n")