使用C语言发送http请求的demo
时间: 2023-10-14 07:05:43 浏览: 152
一个使用C语言socket发送http请求的例子
4星 · 用户满意度95%
以下是一个使用C语言发送HTTP请求的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#define MAX_BUFFER_SIZE 1024
int main(int argc, char *argv[]) {
struct sockaddr_in server_addr;
struct hostent *server;
int socket_fd, port_number, bytes, sent, received, total;
char buffer[MAX_BUFFER_SIZE], request[MAX_BUFFER_SIZE];
if (argc < 3) {
fprintf(stderr, "Usage: %s <hostname> <port_number> <path>\n", argv[0]);
exit(1);
}
port_number = atoi(argv[2]);
/* 创建 socket */
socket_fd = socket(AF_INET, SOCK_STREAM, 0);
if (socket_fd < 0) {
perror("Failed to create socket");
exit(1);
}
/* 获取服务器信息 */
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr, "Failed to get host by name");
exit(1);
}
/* 初始化服务器地址结构 */
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port_number);
memcpy(&server_addr.sin_addr.s_addr, server->h_addr, server->h_length);
/* 连接服务器 */
if (connect(socket_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
perror("Failed to connect to server");
exit(1);
}
/* 构造 HTTP 请求 */
sprintf(request, "GET %s HTTP/1.1\r\nHost: %s:%d\r\nConnection: close\r\n\r\n", argv[3], argv[1], port_number);
/* 发送 HTTP 请求 */
total = strlen(request);
sent = 0;
do {
bytes = write(socket_fd, request + sent, total - sent);
if (bytes < 0) {
perror("Failed to send request");
exit(1);
}
if (bytes == 0) {
break;
}
sent += bytes;
} while (sent < total);
/* 接收 HTTP 响应 */
memset(buffer, 0, sizeof(buffer));
received = 0;
do {
bytes = read(socket_fd, buffer + received, MAX_BUFFER_SIZE - received);
if (bytes < 0) {
perror("Failed to receive response");
exit(1);
}
if (bytes == 0) {
break;
}
received += bytes;
} while (received < MAX_BUFFER_SIZE);
/* 输出 HTTP 响应 */
printf("%s\n", buffer);
/* 关闭 socket */
close(socket_fd);
return 0;
}
```
你可以将以上代码保存到一个名为 `http_request.c` 的文件中,并使用以下命令编译:
```
gcc http_request.c -o http_request
```
然后在终端中运行以下命令来发送 HTTP 请求:
```
./http_request example.com 80 /
```
其中,`example.com` 是要请求的网站的域名,`80` 是要连接的端口号,`/` 是要请求的路径。你可以根据需要修改这些参数。
阅读全文