c语言实现http下载文件
时间: 2023-08-02 18:09:34 浏览: 67
实现 HTTP 下载文件的基本步骤如下:
1. 建立 TCP 连接,发送 HTTP 请求。
2. 接收 HTTP 响应,解析响应头,获取文件大小等信息。
3. 根据文件大小,设置缓冲区大小,循环读取响应体,将数据写入文件。
4. 关闭连接和文件。
以下是一个简单的 C 语言程序,演示如何实现 HTTP 下载文件:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#define BUFFER_SIZE 1024
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("usage: %s url\n", argv[0]);
return 1;
}
// 解析 URL
char *url = argv[1];
char *host = strtok(url, "/");
char *path = strtok(NULL, "");
if (path == NULL) {
path = "/";
}
// 建立 TCP 连接
struct hostent *server = gethostbyname(host);
if (server == NULL) {
perror("gethostbyname failed");
return 1;
}
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("socket failed");
return 1;
}
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(80);
memcpy(&addr.sin_addr.s_addr, server->h_addr, server->h_length);
if (connect(sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
perror("connect failed");
return 1;
}
// 发送 HTTP 请求
char request[BUFFER_SIZE];
sprintf(request, "GET /%s HTTP/1.1\r\nHost: %s\r\n\r\n", path, host);
if (send(sockfd, request, strlen(request), 0) < 0) {
perror("send failed");
return 1;
}
// 接收 HTTP 响应
char response[BUFFER_SIZE];
int n = recv(sockfd, response, BUFFER_SIZE, 0);
if (n < 0) {
perror("recv failed");
return 1;
}
response[n] = '\0';
// 解析响应头
char *content_length = strstr(response, "Content-Length:");
if (content_length == NULL) {
printf("unknown file size\n");
return 1;
}
int file_size = atoi(content_length + strlen("Content-Length:"));
printf("file size: %d\n", file_size);
// 写入文件
FILE *file = fopen("file.txt", "wb");
char buffer[BUFFER_SIZE];
int total = 0;
while (total < file_size) {
n = recv(sockfd, buffer, BUFFER_SIZE, 0);
if (n < 0) {
perror("recv failed");
return 1;
}
fwrite(buffer, sizeof(char), n, file);
total += n;
}
fclose(file);
// 关闭连接
close(sockfd);
printf("file downloaded\n");
return 0;
}
```
注意:以上代码仅供参考,实际使用时需要添加错误处理和其他必要的检查。