You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言手动发送HTTP GET请求返回400 Bad Request问题排查

C语言发送HTTP/1.1 GET请求返回400 Bad Request的解决办法

问题场景

用C语言编写函数,通过socket文件描述符sockfd向本地Apache HTTP服务器发送HTTP/1.1的GET请求,能正常发送请求并接收响应,但始终收到服务器返回的400 Bad Request状态码。

错误代码示例

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define PORT 80
#define BUFFER_SIZE 1024

int main() {
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }

    struct sockaddr_in serv_addr;
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(PORT);
    
    if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
        perror("invalid address");
        close(sockfd);
        exit(EXIT_FAILURE);
    }

    if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
        perror("connection failed");
        close(sockfd);
        exit(EXIT_FAILURE);
    }

    // 错误请求:缺少HTTP/1.1要求的Host头
    char *request = "GET / HTTP/1.1\r\n\r\n";
    send(sockfd, request, strlen(request), 0);

    char buffer[BUFFER_SIZE] = {0};
    read(sockfd, buffer, BUFFER_SIZE);
    printf("Server Response:\n%s\n", buffer);

    close(sockfd);
    return 0;
}

服务器返回的错误响应

HTTP/1.1 400 Bad Request
Date: Wed, 10 Apr 2024 12:34:56 GMT
Server: Apache/2.4.57 (Ubuntu)
Content-Length: 226
Connection: close
Content-Type: text/html; charset=iso-8859-1

400 Bad Request
Bad Request

Your browser sent a request that this server could not understand.

问题原因

HTTP/1.1协议明确要求所有请求必须包含Host头字段,用于指定请求目标的主机名和端口号。Apache服务器严格遵循该规范,当检测到请求缺失Host头时,会直接返回400错误。

解决方法

在GET请求中添加Host头字段,修改后的请求字符串如下:

// 添加Host头后的合法请求
char *request = "GET / HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n";

重新运行程序后,即可收到服务器返回的正常200 OK响应。

内容的提问来源于stack exchange,提问作者coterobarros

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 19:10:59