1. 程式人生 > >C實現的 簡易的http伺服器

C實現的 簡易的http伺服器

#include <stdio.h>
#include <ctype.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

#define PORT 9001
#define QUEUE_MAX_COUNT 5
#define BUFF_SIZE 1024

#define SERVER_STRING "Server: hoohackhttpd/0.1.0\r\n"
 
int main()
{
    /* 定義server和client的檔案描述符 */
    int server_fd = -1; 
    int client_fd = -1; 
 
    u_short port = PORT;
    struct sockaddr_in client_addr;
    struct sockaddr_in server_addr;
    socklen_t client_addr_len = sizeof(client_addr);
 
    char buf[BUFF_SIZE];
    char recv_buf[BUFF_SIZE];
    char hello_str[] = "Hello world!";
 
    int hello_len = 0;
    int on = 1;
 
    /* 建立一個socket */
    server_fd = socket(AF_INET, SOCK_STREAM, 0); 
    if (server_fd == -1) {
        perror("socket");
        exit(-1);
    }   
        
    /* 設定地址複用 */
    ret = setsockpot(server_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
    if (ret < 0)
    {   
        perror("setsockpot failed");
        return -1; 
    }   

    memset(&server_addr, 0, sizeof(server_addr));
    /* 設定埠,IP,和TCP/IP協議族 */
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
        

    /* 繫結套接字到埠 */
    if (bind(server_fd, (struct sockaddr *)&server_addr,
         sizeof(server_addr)) < 0) {
        perror("bind");
        exit(-1);
    }

    /* 啟動socket監聽請求,開始等待客戶端發來的請求 */
    if (listen(server_fd, QUEUE_MAX_COUNT) < 0) {
        perror("listen");
        exit(-1);
    }

    printf("http server running on port %d\n", port);

    while (1) {
        /* 呼叫了accept函式,阻塞了程式,直到接收到客戶端的請求 */
        client_fd = accept(server_fd, (struct sockaddr *)&client_addr,
                   &client_addr_len);
        if (client_fd < 0) {
            perror("accept");
            exit(-1);
        }
        printf("accept a client\n");

        printf("client socket fd: %d\n", client_fd);
        /* 呼叫recv函式接收客戶端發來的請求資訊 */
        hello_len = recv(client_fd, recv_buf, BUFF_SIZE, 0);

        printf("receive %d\n\n", hello_len);

        printf("%s\n", recv_buf);

#if 0
        /* 傳送響應給客戶端 */
        sprintf(buf, "HTTP/1.0 200 OK\r\n");
        send(client_fd, buf, strlen(buf), 0);
        strcpy(buf, SERVER_STRING);
        send(client_fd, buf, strlen(buf), 0);
        sprintf(buf, "Content-Type: text/html\r\n");
        send(client_fd, buf, strlen(buf), 0);
        strcpy(buf, "\r\n");
        send(client_fd, buf, strlen(buf), 0);
        sprintf(buf, "Hello World\r\n");
        send(client_fd, buf, strlen(buf), 0);
#endif
        /* 關閉客戶端套接字 */
        close(client_fd);
    }

    close(server_fd);

    return 0;
}