美文网首页
c语言实现简单http服务器

c语言实现简单http服务器

作者: 一路向后 | 来源:发表于2021-10-31 17:24 被阅读0次

    1.源码实现

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include <unistd.h>
    #include <fcntl.h>
    
    #define SERVER_PORT 8008
    #define MESSAGE "HTTP/1.1 200 OK\r\nContent-Length: 11\r\n\r\nhello world"
    
    int main()
    {
        struct sockaddr_in srvaddr;
        int locfd;
        int sockopt = 1;
        int res;
    
        /*创建一个套接字*/
        locfd = socket(AF_INET, SOCK_STREAM, 0);
        if(locfd < 0)
        {
            printf("create socket error!\n");
            return -1;
        }
    
        printf("socket ready!\n");
    
        srvaddr.sin_family = AF_INET;
        srvaddr.sin_port = htons(SERVER_PORT);
        srvaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    
        setsockopt(locfd, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof(int));
    
        /*bind, 将网络地址与端口绑定*/
        res = bind(locfd, (struct sockaddr *)&srvaddr, sizeof(srvaddr));
        if(res < 0)
        {
            printf("bind error!\n");
            close(locfd);
            return -1;
        }
    
        printf("bind ready!\n");
    
        /*listen, 监听端口*/
        listen(locfd, 10);
    
        printf("等待来自客户端的连接......\n");
    
        while(1)
        {
            struct sockaddr_in cliaddr;
            socklen_t len = sizeof(cliaddr);
            int clifd;
    
            clifd = accept(locfd, (struct sockaddr *)&cliaddr, &len);
            if(clifd < 0)
            {
                printf("accept error!\n");
                close(locfd);
                return -1;
            }
    
            /*输出客户机的信息*/
            char *ip = inet_ntoa(cliaddr.sin_addr);
    
            printf("客户机: %s连接到本服务器成功!\n", ip);
    
            /*输出客户机请求的信息*/
            char buff[1024] = {0};
            int size = read(clifd, buff, sizeof(buff));
    
            printf("Request information: ");
    
            printf("%s\n", buff);
    
            printf("%d bytes\n", size);
    
            write(clifd, MESSAGE, strlen(MESSAGE));
    
            close(clifd);
        }
    
        close(locfd);
    
        return 0;
    }
    

    2.编译源码

    $ gcc -o httpd httpd.c -std=c89
    

    3.运行及其结果

    $ ./httpd
    

    在浏览器地址栏输入http://127.0.0.1:8008/即可访问

    相关文章

      网友评论

          本文标题:c语言实现简单http服务器

          本文链接:https://www.haomeiwen.com/subject/qmwoaltx.html