gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:25:16 28 4
gpt4 key购买 nike

一个简单的 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);
}
}

最佳答案

嗯,根据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) */
}

关于C Web 服务器 - 如何获取 URI?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42266418/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com