用C语言实现简单的web server

参考链接:
http://www.linuxhowtos.org/C_C++/socket.htm //强烈推荐看完
http://www.cleey.com/blog/single/id/789.html

#include <ctype.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#define buffer_size 5000
void error(char *msg)
{
    perror(msg);
    exit(1);
}

char *HttpRes = "HTTP/1.1 200 OK\r\n"
                "Connection: Close\r\n"
                "Server: Moon V1.0\r\n"
                "Content-Lenghth: %d\r\n "
                "Content-Type: %s\r\n\r\n";

void http_response(int sock, char *content);

int main(int argc, char *argv[])
{
    int sockfd, portno, clilen, newsockfd, n;
    char buffer[buffer_size];
    struct sockaddr_in serv_addr, cli_addr;
    if (argc < 2) {
        fprintf(stderr, "ERROR,no port provided!");
        exit(1);
    }
    int count = 0;

    sockfd = socket(AF_INET, SOCK_STREAM, 0);

    if (sockfd < 0)
        error("ERROR on binding!");

    bzero((char *)&serv_addr, sizeof(serv_addr));
    portno = atoi(argv[1]);
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(portno);
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);

    if (bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
        error("ERROR on binding!");

    if (listen(sockfd, 5) < 0) {
        perror("listen");
        exit(-1);
    }

    clilen = sizeof(cli_addr);

    while (1) {
        newsockfd = accept(sockfd, (struct sockaddr *)&cli_addr, &clilen);
        printf("%d:\n", ++count);
        if (newsockfd < 0)
            error("ERROR on accept!");
        puts("We accept a client!\n");

        bzero(buffer, buffer_size);
        n = recv(newsockfd, buffer, sizeof(buffer), 0);
        if (n < 0)
            error("look here");

        fputs(buffer, stdout);

        http_response(newsockfd, "Now you see me");


        close(newsockfd);
    }
    fputs("Bye~", stdout);
    close(sockfd);

    return 0;
}

void http_response(int sockfd, char *content)
{
    char Http_Header[buffer_size], Http_Full[buffer_size];
    int len = strlen(content);
    sprintf(Http_Header, HttpRes, len, "text/html");
    len = sprintf(Http_Full, "%s%s", Http_Header, content);
    send(sockfd, Http_Full, len, 0);
}

编译后在终端运行
gcc server.c -o server
./server YOUR_PORT
把YOUR_PORT替换为你想要的端口
然后打开浏览器
输入
YOUR_IP:YOUR_PORT

猜你喜欢

转载自www.cnblogs.com/tennant/p/9103913.html