修改三个宏定义即可
#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;
}