我使用 C 语言编写了一个 Web 服务器。我可以访问服务器http://myhostname:protnum/index.html
但是当我用朋友的电脑访问同一个地址时,却说无法访问网页。
该文件是 webserv.c,使用 ./webserv 12345 启动服务器(在终端中)
为什么我朋友的电脑无法访问服务器?以下是 webserv.c 文件:
int main(int argc, char const *argv[])
{
int sock, fd;
FILE *fpin;
char request[BUFSIZ];
if (argc == 1) {
fprintf(stderr, "usage: ws portnum\n");
exit(1);
}
sock = make_server_socket( atoi(argv[1]) );
if (sock == -1)
exit(2);
/*main loop here*/
while (1) {
/*take a call and buffer it*/
fd = accept(sock, NULL, NULL);
fpin = fdopen(fd, "r");
/*read request*/
fgets(request, BUFSIZ, fpin);
printf("Got a call: request = %s", request);
read_til_crnl(fpin);
/*do what client asks*/
process_rq(request, fd);
fclose(fpin);
}
return 0;
}
int make_server_socket_q(int portnum, int backlog)
{
struct sockaddr_in saddr;
struct hostent *hp;
char hostname[HOSTLEN];
int sock_id;
sock_id = socket(PF_INET, SOCK_STREAM, 0);
if (sock_id == -1)
return -1;
/*build address abd bind it to socket*/
bzero((void *)&saddr, sizeof(saddr));
gethostname(hostname, HOSTLEN);
hp = gethostbyname(hostname);
bcopy((void *)hp->h_addr, (void *)&saddr.sin_addr, hp->h_length);
saddr.sin_port = htons(portnum);
saddr.sin_family = AF_INET;
if (bind(sock_id, (struct sockaddr *)&saddr, sizeof(saddr)) != 0)
return -1;
if (listen(sock_id, backlog) != 0)
return -1;
return sock_id;
}
void process_rq(char *request, int fd)
{
char cmd[BUFSIZ], arg[BUFSIZ];
/*create a new process and return if not the child*/
if (fork() != 0)
return;
strcpy(arg, "./");
if (sscanf(request, "%s%s", cmd, arg+2) !=2)
return;
if (strcmp(cmd, "GET") != 0)
cannot_do(fd);
else if (not_exist(arg))
do_404(arg, fd);
else if (isadir(arg))
do_ls(arg, fd);
else if (ends_in_cgi(arg))
do_exec(arg, fd);
else
do_cat(arg, fd);
}