嗨,我正在用 C 编写一个简单的 Web 服务器,它只处理从浏览器发送的简单 get 和 post 请求。我对 C 不是很熟悉,所以调试很痛苦,但我已经编译了它,但在尝试查看网页时,我不断地从浏览器收到 err_connection_reset 响应。我已将其范围缩小到不进入用于在打开的套接字上侦听但不会进入的主循环,这是我的主要功能
int main(int argc, char *argv[])
{
printf("in main");
int portno; // port number passed as parameter
portno = atoi(argv[1]); // convert port num to integer
if (portno < 24)
{
portno = portno + 2000;
}
else if ((portno > 24) && (portno < 1024))
{
portno = portno + 1000;
}
else
{
;
}
// Signal SigCatcher to eliminate zombies
// a zombie is a thread that has ended but must
// be terminated to remove it
signal(SIGCHLD, SigCatcher);
int sockfd; // socket for binding
int newsockfd; // socket for this connection
int clilen; // size of client address
int pid; // PID of created thread
// socket structures used in socket creation
struct sockaddr_in serv_addr, cli_addr;
// Create a socket for the connection
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
error("ERROR opening socket\n");
}
// bzero zeroes buffers, zero the server address buffer
bzero((char *)&serv_addr, sizeof(serv_addr));
// set up the server address
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
// bind to the socket
if (bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
error("ERROR on binding. Did you forget to kill the last server?\n");
listen(sockfd, 5); // Listen on socket
clilen = sizeof(cli_addr); // size of client address
while (1)
{ // loop forever listening on socket
newsockfd = accept(sockfd, (struct sockaddr *)&cli_addr, (socklen_t *) & clilen);
if (newsockfd < 0)
error("ERROR on accept");
// Server waits on accept waiting for client request
// When request received fork a new thread to handle it
pid = fork();
if (pid < 0)
error("ERROR on fork\n");
if (pid == 0)
{ // request received
close(sockfd);
// Create thread and socket to handle
httpthread(newsockfd, cli_addr);
exit(0);
}
else
close(newsockfd);
} /* end of while */
return 0; /* we never get here */
}