在阅读“计算机系统:程序员的视角”这本书时,在网络编程一章中,我看到了一个函数:
int open_clientfd(char *hostname, char *port) {
int clientfd;
struct addrinfo hints, *listp, *p;
/* Get a list of potential server addresses */
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_socktype = SOCK_STREAM; /* Open a connection */
hints.ai_flags = AI_NUMERICSERV; /* ... using a numeric port arg. */
hints.ai_flags |= AI_ADDRCONFIG; /* Recommended for connections */
Getaddrinfo(hostname, port, &hints, &listp);
/* Walk the list for one that we can successfully connect to */
for (p = listp; p; p = p->ai_next) {
/* Create the socket descriptor */
if ((clientfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) < 0)
continue; /* Socket failed, try the next */
if (connect(clientfd, p->ai_addr, p->ai_addrlen) != -1)
break; /* Success */
Close(clientfd); /* Connect failed, try another */
}
/* Clean up */
Freeaddrinfo(listp);
if (!p) /* All connects failed */
return -1;
else /* The last connect succeeded */
return clientfd;
}我不理解的是这里的这行Close(clientfd); /* Connect failed, try another */,因为如果套接字创建失败,它将继续,如果它成功,它将中断for循环,似乎这行永远不会有机会执行?
发布于 2019-01-15 17:49:06
当socket成功时,您就打开了一个套接字。如果connect失败,套接字仍然存在,必须关闭。循环的下一个周期将使用列表中的下一个地址,该地址可能需要为socket调用提供不同的参数。这就是为什么现有的套接字没有被重用的原因。
https://stackoverflow.com/questions/54196237
复制相似问题