gpt4 book ai didi

c - 实现 HEAD 和 GET 请求,C 中的简单 Web 服务器

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:23:18 27 4
gpt4 key购买 nike

<分区>

我正在用 C 语言制作一个简单的 Web 服务器,我需要处理简单版和完整版的 http 1.0 方法 HEAD 和 GET 请求。所有其他请求应导致状态代码 501。这是我第一次编写 Web 服务器程序,找到你需要的东西有点困难。有人能帮我走上正轨吗?我如何处理这些请求?到目前为止我的代码:

#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 <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>

#define SIZE 512




int main(int argc, char *argv[])
{
int portnumber;
int sockfd; //for new client connections
int sockfd_current; //for accepted clients
struct sockaddr_in sockIn;
struct sockaddr_in portIn;
char buffert[SIZE];
int addrlen;
char ipAddress[INET_ADDRSTRLEN]; //incomming IP-address to server with length


portnumber= atoi(argv[1]); //second parameter passed from main into portnumber


if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) //trying to create socket address-family
{
perror ("socket");
exit(1);
}

memset(&sockIn, 0, sizeof(sockIn)); //assign memory and set socket address structure
sockIn.sin_family= AF_INET;
sockIn.sin_addr.s_addr =INADDR_ANY;
sockIn.sin_port = htons(portnumber); //assign port to network byteorder: hostToNetwork

if(bind(sockfd, (struct sockaddr *) &sockIn, sizeof(sockIn)) == -1)//trying to assign address to socket
{
perror("bind");
exit(1);
}

if(listen(sockfd, 10) == -1) //trying to Listen for clients that fulfills the requirements
{
perror("listen");
exit(1);
}
addrlen = sizeof(portIn);
if((sockfd_current = accept(sockfd, (struct sockaddr*) &portIn, (socklen_t*) &addrlen)) == -1) //trying to Create a new socket for the accepted client
{
perror("accept");
exit(1);
}

//Start communication aka HEAD/GET from client...
printf("Accepting connection...\n\n");
if(recv(sockfd_current, buffert, sizeof(buffert), 0) == -1) //trying to recive message from client
{
perror("Failed to recive request from client");
exit(1);
}

inet_ntop(AF_INET, &portIn.sin_addr, ipAddress, sizeof(ipAddress)); //convert binary-ip from client to "networkToPresentable" string
printf("Request from %s:%i\n", ipAddress, ntohs(portIn.sin_port));
printf("Message: %s\n", buffert);


//Responds to clients request
printf("Send Response:\n\n");
fgets(buffert, SIZE - 1, stdin);

if(send(sockfd_current, buffert, strlen(buffert) + 1, 0) == -1)
{
perror("send");
exit(1);
}


close(sockfd_current);
close(sockfd);
return 0;
}

我得到的任务是只做服务器而不是客户端,所以我应该只需要处理请求。

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