C Web服务器 - 如何获取URI?

时间:2017-02-16 06:23:24

标签: c webserver

简单的 C Web服务器:如何获取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);
  }
}

1 个答案:

答案 0 :(得分:0)

嗯,根据RFC 7230GET查询应如下所示:

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) */
}