http服务器下载文件

时间:2021-06-30 17:49:46

http服务器下载文件

代码如下:

mydown.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
//#include "tcp.h"

#define DEFAULT_PORT 80

int main( int argc, char ** argv )
{
    char *p = NULL;
    char path[1024];
    char hostname[100];
    char *purl = argv[1];
    char request[200];    
    char recv_buf[1400];
    int recv_count;
    int sock_fd;
    int ret;
    int iLoop = 0;
    struct hostent *host;
    struct sockaddr_in server_addr;

    if(argc != 2) {
        printf("Usage: %s URL\n", argv[0]);
        exit(1);
    }

    p = strchr(purl, ':');        /* http://www.baidu.com/filename.txt */
    p = strchr(p + 3, '/');      /* https://www.baidu.com/filename.txt */
    strcpy(path, p);
    *p = '\0';
    printf("---path: %s---\n", path);

    p = strchr(purl, ':');      /* https://www.baidu.com/filename.txt */
    strcpy(hostname, p + 3);
    printf("---hostname: %s---\n", hostname);

    printf("正在进行域名解析: %s...\n", hostname);
    host = gethostbyname(hostname);
    if(host == NULL) {
        perror("gethostbyname");
        exit(1);
    }

    sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(DEFAULT_PORT);
    memcpy(&server_addr.sin_addr, host->h_addr, sizeof(int));

    printf("正在连接服务器: %s...\n", hostname);
    ret = connect(sock_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr_in));
    if(ret == -1) {
        perror("connect");
        exit(2);
    }
    
    sprintf(request, "GET %s HTTP/1.1\r\nHost: %s: %d\r\nRange: bytes=0-\r\n\r\n", path, hostname, DEFAULT_PORT);
    //sprintf(request, "GET %s HTTP/1.1\r\nHost: %s: %d\r\nRange: bytes=1-\r\n\r\n", path, hostname, DEFAULT_PORT);
    //sprintf(request, "GET %s HTTP/1.1\r\nHost: %s: %d\r\nRange: bytes=2-\r\n\r\n", path, hostname, DEFAULT_PORT);
    //sprintf(request, "HEAD %s HTTP/1.1\r\nHost: %s: %d\r\nRange: bytes=1-\r\n\r\n", path, hostname, DEFAULT_PORT);

    printf("正在发送下载请求...\n");
    send(sock_fd, request, strlen(request)+1, 0);    
    printf("正在接受服务器数据...\n");

    while(1) {
        iLoop++;
        bzero(recv_buf, sizeof(recv_buf));
        recv_count = recv(sock_fd, recv_buf, sizeof(recv_buf) - 1, 0);
        if((recv_count == 0) /* || (recv_count < sizeof(recv_buf) - 1) */) {
            //printf("接受完毕(iLoop = %d).\n", iLoop);
            printf("接受完毕(recv_count = %d).\n", iLoop);
            break;
        }
        printf("%s", recv_buf);
        //write(write_fd, recv_buf, recv_count);
    }

    close(sock_fd);
    return 0;
}

编译链接运行, 输出如下:

http服务器下载文件

可能是http请求的头域中缺少必须的头域信息. 收到了400错误.