2017-02-16 5 views
1

シンプルC Webサーバー:URIを取得するには?C Web Server - URIを取得するには?

また、
おそらく、すべての着信生データを表示する方法がありますか?

GETリクエスト全体のようにURLと一緒に?

ウェブを検索しましたが、情報が見つかりませんでした。

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <sys/socket.h> 
#include <netinet/in.h> 
#include <netdb.h> 
#include <arpa/inet.h> 
#include <err.h> 

char response[] = "HTTP/1.1 200 OK\r\n" 
"Content-Type: text/html; charset=UTF-8\r\n\r\n" 
"test\r\n"; 

int main() 
{ 
    int one = 1, client_fd; 
    struct sockaddr_in svr_addr, cli_addr; 
    socklen_t sin_len = sizeof(cli_addr); 

    int sock = socket(AF_INET, SOCK_STREAM, 0); 
    if (sock < 0) 
    err(1, "can't open socket"); 

    setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int)); 

    int port = 82; 
    svr_addr.sin_family = AF_INET; 
    svr_addr.sin_addr.s_addr = INADDR_ANY; 
    svr_addr.sin_port = htons(port); 

    if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) { 
    close(sock); 
    err(1, "Can't bind"); 
    } 

    listen(sock, 5); 
    while (1) { 
    client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len); 
    printf("got connection\n"); 

    if (client_fd == -1) { 
     perror("Can't accept"); 
     continue; 
    } 

    write(client_fd, response, sizeof(response) - 1); /*-1:'\0'*/ 
    close(client_fd); 
    } 
} 

答えて

0

まあ、RFC 7230によると、GETクエリがどのように見えるはずです:クライアントが接続したときに

ので
GET /index.html HTTP/1.1 
Host: www.example.org 

、あなたはクライアントからの問合せを読んで、それを解析する必要があります。

/* data to store client query, warning, should not be big enough to handle all cases */ 
char query[1024] = ""; 
char page[128] = ""; 
char host[128] = ""; 

/* read query */ 
if (read(client_fd, query, sizeof query-1) > 0) 
{ 
    char *tok; 
    char sep[] * "\r\n"; 
    char tmp[128]; 
    /* cut query in lines */ 
    tok = strtok(query, sep); 

    /* process each line */ 
    while (tok) 
    { 
     /* See if line contains 'GET' */ 
     if (1 == sscanf(tok, "GET %s HTTP/1.1", tmp)) 
     { 
      strcpy(page, tmp); 
     } 
     /* See if line contains 'Host:' */ 
     else if (1 == sscanf(tok, "Host: %s", tmp)) 
     { 
      strcpy(host, tmp); 
     } 
     /* get next line */ 
     tok = strtok(query, sep); 
    } 
    /* print got data */ 
    printf("wanted page is: %s%s\n", host, page); 
} 
else 
{ 
    /* handle the error (-1) or no data to read (0) */ 
} 
関連する問題