简体   繁体   English

HTTP 错误:C 中套接字编程中的错误请求

[英]HTTP error: Bad request in socket programming in C

I wrote a basic C program that establishes a connection with the IP address of google.com and then starts receiving data from client.我写了一个基本的 C 程序,它与google.com的 IP 地址建立连接,然后开始从客户端接收数据。

But firstly, during compilation the following warning is generated:但首先,在编译期间会生成以下警告:

test.c:12:25: warning: implicit declaration
      of function 'inet_addr' is invalid in
      C99 [-Wimplicit-function-declaration]
address.sin_addr.s_addr=inet_addr("2...
                        ^
1 warning generated.

Secondly, on running the program, the following output is generated:其次,在运行程序时,会生成以下输出:

HTTP/1.0 400 Bad Request
Content-Type: text/html; charset=UTF-8
Referrer-Policy: no-referrer
ContGET/HTTP/1.1

What changes can I make in my code to successfully receive data from an HTTP server ?为了成功从 HTTP 服务器接收数据,我可以对代码进行哪些更改?

#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<stdlib.h>

int main()
{
    int mySocket = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in address;
    address.sin_port = htons(80);
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = inet_addr("216.58.200.196");
    connect(mySocket, (struct sockaddr *)&address, sizeof(address));
    char msg[21] = "GET/HTTP/1.1\r\n\r\n";
    send(mySocket, msg, 21, 0);
    char msgRecv[100];
    recv(mySocket, msgRecv, 100, 0);
    printf("%s", msgRecv);
}

Your code has many faults (lack of error handling, misusing send() , recv() and printf() , etc), but the main cause of the HTTP failure is because your HTTP request is malformed.您的代码有很多错误(缺乏错误处理、滥用send()recv()printf()等),但导致 HTTP 失败的主要原因是您的 HTTP 请求格式错误。

If you read the HTTP 1.1 protocol specification, RFC 2616 and its successors RFCs 7230-7235, you will see that you are missing required space characters between GET and / , and between / and HTTP , and that you are also missing a required Host header.如果您阅读 HTTP 1.1 协议规范、 RFC 2616及其后续 RFC 7230-7235,您会发现在GET/之间以及/HTTP之间缺少必需的空格字符,并且还缺少必需的Host标头.

At a bare minimum, your HTTP request needs to look like this instead:至少,您的 HTTP 请求需要如下所示:

char msg[] = "GET / HTTP/1.1\r\nHost: google.com\r\n\r\n";

Once you have that working, look at this answer for the kind of logic you will need to implement afterwards to receive the server's response properly (a single call to recv() won't cut it, not even close).一旦您开始工作,请查看此答案,了解您之后需要实现的逻辑类型以正确接收服务器的响应(对recv()的单个调用不会切断它,甚至不会关闭)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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