【问题标题】:C: POST json request using sockets returns 400 bad requestC:使用套接字的 POST json 请求返回 400 错误请求
【发布时间】:2021-04-10 20:50:27
【问题描述】:

我使用请求日志从 Python 获得原始请求,其中状态为 200:

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main(void) {
    struct addrinfo hints, *res;
    int sockfd;
    char buf[2056];
    int byte_count;
    memset(&hints, 0,sizeof hints);
    hints.ai_family=AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    getaddrinfo("example.com","443", &hints, &res);
    sockfd = socket(res->ai_family,res->ai_socktype,res->ai_protocol);
    printf("Connecting...\n");
    connect(sockfd,res->ai_addr,res->ai_addrlen);
    printf("Connected!\n");
    char *header = "POST /abc HTTP/1.1\r\nHost: example.com\r\nAccept-Encoding: gzip, deflate\r\nAccept: application/json\r\nConnection: keep-alive\r\nContent-Type: application/json\r\nContent-Length: 22\r\n\r\n{\"abcdeghiewf\": \"abc\"}";
    send(sockfd,header,strlen(header),0);
    printf("POST Sent...\n");
    byte_count = recv(sockfd,buf,sizeof(buf),0);
    printf("recv()'d %d bytes of data in buf\n",byte_count);
    printf("%.*s",byte_count,buf);
    return 0;
}

这是我从 Python 的 requests 模块收到的请求:

send: b'POST /abc HTTP/1.1\r\nHost: example.com\r\nAccept-Encoding: gzip, deflate\r\nAccept: application/json\r\nConnection: keep-alive\r\nContent-Type: application/json\r\nContent-Length: 22\r\n\r\n'

send: b'{"abcdeghiewf": "abc"}'

【问题讨论】:

  • 附带说明,此代码中没有任何错误处理。你调用的任何函数都可能失败,你没有检查。

标签: c sockets


【解决方案1】:

您正在连接到端口 443,这是默认的 HTTPS TLS 端口。但是,在该会话中交换 HTTP 消息之前,您不会协商 TLS 握手以建立加密会话。

服务器在需要加密的端口上检测到未加密的 HTTP 消息,因此它正在发回未加密的响应,并可能终止连接。

所以,您需要:

  • 连接到端口 80 而不是 443

  • 正确实施 TLS,例如使用 OpenSSL 或任何其他类似的加密库/API。

【讨论】:

  • 我尝试使用 openssl 但我并没有真正理解它,你能提供一个简单的例子吗?谢谢
  • @kkkkkkkkkkkkkkkkkk 网上有很多关于如何使用 OpenSSL 的教程,甚至整本书
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-02
  • 1970-01-01
  • 1970-01-01
  • 2015-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多