C语言Socket实现Http的post请求

修改三个宏定义即可

#define HOST "192.168.1.133" //主机

#define PORT 80 //端口

#define POST_DATA "post_test=444&post_val=555" //内容

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

#define HOST "192.168.1.133"
#define PORT 80
#define POST_DATA "post_test=444&post_val=555"
#define POST_DATA_LENGTH strlen(POST_DATA)

int main() {
    int sockfd;
    struct sockaddr_in server_addr;
    struct hostent *server;

    // 创建套接字
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        perror("Error opening socket");
        exit(1);
    }

    // 获取服务器的IP地址
    server = gethostbyname(HOST);
    if (server == NULL) {
        fprintf(stderr,"Error: no such host\n");
        exit(1);
    }

    // 设置服务器地址结构
    bzero((char *) &server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    bcopy((char *)server->h_addr, (char *)&server_addr.sin_addr.s_addr, server->h_length);
    server_addr.sin_port = htons(PORT);

    // 连接到服务器
    if (connect(sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
        perror("Error connecting");
        exit(1);
    }

    // 构造HTTP请求
    char request[1024];
    sprintf(request, "POST /set HTTP/1.1\r\n"
                      "Host: %s\r\n"
                      "Content-Type: application/x-www-form-urlencoded\r\n"
                      "Content-Length: %zu\r\n"
                      "\r\n"
                      "%s", HOST, POST_DATA_LENGTH, POST_DATA);

    // 发送HTTP请求
    if (send(sockfd, request, strlen(request), 0) < 0) {
        perror("Error sending request");
        exit(1);
    }

    // 接收并显示服务器的响应
    char response[4096];
    int bytes_received = recv(sockfd, response, sizeof(response), 0);
    if (bytes_received < 0) {
        perror("Error receiving response");
        exit(1);
    }
    printf("Response from server:\n");
    fwrite(response, 1, bytes_received, stdout);

    // 关闭套接字
    close(sockfd);

    return 0;
}
相关推荐
胖咕噜的稞达鸭44 分钟前
自定义shell命令行解释器自制
java·开发语言
草莓熊Lotso44 分钟前
Git 分支管理:从基础操作到协作流程(本地篇)
大数据·服务器·开发语言·c++·人工智能·git·sql
报错小能手1 小时前
C++异常处理 终极及总结
开发语言·c++
雨落在了我的手上1 小时前
C语言入门(二十二):字符函数和字符串函数(2)
c语言
qq_401700414 小时前
嵌入式用Unix时间的优势及其C语言转换
服务器·c语言·unix
tobebetter95276 小时前
How to manage python versions on windows
开发语言·windows·python
9***P3347 小时前
PHP代码覆盖率
开发语言·php·代码覆盖率
CoderYanger7 小时前
优选算法-栈:67.基本计算器Ⅱ
java·开发语言·算法·leetcode·职场和发展·1024程序员节
jllllyuz8 小时前
Matlab实现基于Matrix Pencil算法实现声源信号角度和时间估计
开发语言·算法·matlab
多多*8 小时前
Java复习 操作系统原理 计算机网络相关 2025年11月23日
java·开发语言·网络·算法·spring·microsoft·maven