http网页文件下载服务器

  1. index.html

    1
    Hello from server, it works!
  2. server.c

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    #include <sys/socket.h>
    #include <string.h>
    #include <fcntl.h>
    #include <sys/sendfile.h>
    #include <unistd.h>
    #include <netinet/in.h>

    int main()
    {
    int s = socket(AF_INET,SOCK_STREAM,0);

    struct sockaddr_in addr={
    AF_INET,
    0x901f,
    0
    };

    bind(s, (struct sockaddr*)&addr, sizeof(addr));

    listen(s, 10);

    int client_fd = accept(s, 0, 0);

    char buffer[256] = {0};
    recv(client_fd, buffer, 256, 0);

    //GET /file.html .....

    char *f = buffer + 5;
    *strchr(f, ' ') = 0;
    int opened_fd = open(f, O_RDONLY);

    sendfile(client_fd, opened_fd, 0, 256);
    close(opened_fd);
    close(client_fd);
    close(s);

    return 0;
    }
  3. 编译运行

    1
    2
    gcc server.c
    strace ./a.out
  4. 运行后浏览器访问或者以下命令下载

    1
    wget localhost:8080/index.html
  5. 下载成功