为什么还要在python套接字请求中包含主机?

时间:2018-02-11 09:15:24

标签: python sockets

我看到人们从主机和端口创建套接字对象但后来也发送GET请求的示例,并在http请求中包含Host头。

import socket

HOST = 'daring.cwi.nl'
PORT = 80

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    s.sendall("GET / HTTP/1.1\r\n\r\nHost: daring.cwi.nl")
    data = s.recv(1024)
print('Received', repr(data))

为什么我们需要提供一次主机来创建套接字对象并再次发送请求?

2 个答案:

答案 0 :(得分:0)

首先,如果你只是使用普通的tcp连接,你可以发送任何你想要的东西,你可以Get

其次,在您的代码中,它模拟/?parameter1=value1&parameter2=value2 http请求。要发送参数,您只需要在url之后将它们连接起来。 Host

最后,为什么我们需要再次加入Host?假设您要将此请求发送到负载平衡服务器,如果没有明确发送,应用程序服务器将无法实现Warning: imagecreatefromstring(): gd-png: fatal libpng error: Read Error: truncated data in /home/retweety/public_html/uploadr/get.php on line 92 Warning: imagecreatefromstring(): gd-png error: setjmp returns error condition in /home/retweety/public_html/uploadr/get.php on line 92 Warning: imagecreatefromstring(): Passed data is not in 'PNG' format in /home/retweety/public_html/uploadr/get.php on line 92 Warning: imagecreatefromstring(): Couldn't create GD Image Stream out of Data in /home/retweety/public_html/uploadr/get.php on line 92 Warning: imagecrop() expects parameter 1 to be resource, boolean given in /home/retweety/public_html/uploadr/get.php on line 93 Warning: imagepng() expects parameter 1 to be resource, null given in /home/retweety/public_html/uploadr/get.php on line 96 Warning: imagedestroy() expects parameter 1 to be resource, null given in /home/retweety/public_html/uploadr/get.php on line 97

答案 1 :(得分:0)

HTTP标准(至少版本1.1)需要Host标头,即定义与Web服务器通信的协议的标准。这样做的原因是您可以让多个域共享相同的IP地址,因此Web服务器需要找出您要访问的域。由于较低层(即TCP)不包含此信息,而只包含您需要在应用层(即HTTP)提供此信息的IP地址。

至于使用connect内的主机名:实际上不需要这个,你也可以在那里提供IP地址。提供主机名而不是IP时它所做的就是查找主机的IP地址并连接到它。