c - 如何使用 IP 地址形成 GET HTTP 请求

标签 c sockets http networking http-get

当我在 C 中使用下面的 GET HTTP 请求时,我不断收到 400 Bad Request 但当我使用字符串字符 IP 地址(例如:www.wwe.com/index. php):

GET %s HTTP/1.0\r\nHost: %s\r\nConnection: Keep-Alive\r\n\r\n

GET 之后的 %s 被替换为类似这样的内容:http://54.236.192.188/index.php 并且 Host 值由 hostent 结构的 h_name 字符串值提供。

所以一个请求看起来像这样:

GET http://54.236.192.188/index.php HTTP/1.0
Host: ec2-54-236-192-188.compute-1.amazonaws.com
Connection: Keep-Alive

我在这里做错了什么?

最佳答案

GET 的参数本身应该只是资源路径,Host header 应该是请求发送到的机器的域/主机,由原始 URL 指定。

要请求 http://www.wwe.com/index.phpGET 请求如下所示:

GET /index.php HTTP/1.1
Host: www.wwe.com
...

要请求 http://54.236.192.188/index.phpGET 请求如下所示:

GET /index.php HTTP/1.1
Host: 54.236.192.188
...

但是,如果服务器在同一个 IP 地址上运行多个网站,则不能在 rquest 中提供 IP 地址。 Host header 告诉服务器要访问哪个特定网站。

除非需要,否则应使用 HTTP/1.1 而不是 HTTP/1.0。例如,HTTP/1.0 默认不支持 Keep-AliveHost header 是 HTTP 1.1 所必需的。

关于c - 如何使用 IP 地址形成 GET HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34802503/

相关文章:

c - fprintf 上的段错误(假定)有效的 FILE 指针

java - IIS 405..server.tas 文件

http - Blazor WebAssembly : detect from which site the user came from

javascript - 从浏览器加载文件,无需网络服务器

c - 冒泡排序 C 中的链表

c - 系统和CreateProcess()

c - 编码(marshal)处理/解封处理与序列化/反序列化之间有什么区别?

java - 通过 Socket 发送的图像流 - 服务器死锁问题

python - 我如何编写与扭曲服务器通信的东西?

python - 无法使用 OpenSSL 的 ssl.SSLContext() 在 Python 客户端中接收对等证书