我有一个教科书 TCP 服务器。其中我在事件套接字上使用接受功能。注意:我已经注释掉了在 main 中监听 listenfd 的调用。
#include <stdlib.h>
#include <stdio.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <string.h>
void do_work(int sockfd, int lisfd)
{
printf("Child's process id is %d\n", getpid());
close(lisfd);
const int MAXLINE = 30;
char buff[MAXLINE];
time_t ticks;
ticks = time(NULL);
snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks));
write(sockfd, buff, strlen(buff));
close(sockfd);
exit(0);
}
//argc and argv include the program name itself too in the count and array
int main(int argc, char** argv[])
{
int listenfd, connfd;
const int IPLEN = 50;
//max number of connections that server can handle simultaneously
const int LISTENQ = 10;
struct sockaddr_in servaddr,cliaddr;
char cliip[IPLEN];
socklen_t len;
const int PORT = 8088;
if ((listenfd = socket(AF_INET, SOCK_STREAM, 0) ) < 0)
{
printf("listenning socket error %s\n", strerror(errno));
exit(-1);
}
//initialize sockaddr stuctures to zero
bzero(&cliaddr, sizeof(cliaddr));
bzero(&servaddr, sizeof(servaddr));
//initialize value-result argument to accept
len = sizeof(cliaddr);
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
// INADDR_ANY means that socket bound to this servaddr can accept connection
// from any of the interface available on the system
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
{
printf("bind error %s\n", strerror(errno));
exit(-1);
}
//listen(listenfd, LISTENQ);
printf("Parent's process id is %d\n", getpid());
for (int i = 0; i < 2; i++)
//for(;;)
{
connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &len);
printf("accepting connection from ip %s on port %lu\n",
inet_ntop(AF_INET, &cliaddr.sin_addr, &cliip, sizeof(cliip)), ntohl(cliaddr.sin_port));
pid_t childpid;
if ((childpid = fork()) == 0)
{
do_work(connfd,listenfd);
}
// if you don't close it here, then connfd shall remain open in parent process and EOF shall not be issued as FIN segment shall not be sent by tcp
close(connfd);
}
}
现在,当我通过一个简单的客户端连接到它时,它会给我这样的输出。
Parent's process id is 11145
accepting connection from ip 0.0.0.0 on port 0
accepting connection from ip 0.0.0.0 on port 0
Child's process id is 11146
Child's process id is 11147
我想理解的是:这里的0.0.0.0是什么意思? (谷歌说这意味着这里没有 tcp/ip 连接。)但我无法正确看待它。有什么帮助吗?
最佳答案
最可能是对 accept()
的调用失败的。
你应该测试是否accept()
返回 -1
在调查 cliaddr
之前.
还有你显示的代码我错过了 close()
在第一个 do_Work()
之后列出套接字(在 accept()
中) .任何以下 accept()
虽然肯定会失败。fork()
的电话
根据 Duck 的评论:
不过只要调用listen()
被注释掉了 accept()
必须失败。
关于c - 解释在主动套接字(而不是被动套接字)上调用时接受函数的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18742888/