在阅读“计算机系统:程序员的观点”一书时,在“网络编程”一章中,我看到了这样一个功能:
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
}在这个函数中,书中说:“open_clientfd函数与运行在主机名上的服务器建立连接,并监听端口号端口上的连接请求。”
因此,我理解主机名用于客户端,端口用于客户机-服务器事务上的服务器。
我的怀疑来自于代码Getaddrinfo(主机名、端口和提示,&listp);
由于getaddrinfo的主机和服务参数是套接字地址的两个组件(正如书中所述),我认为这个open_clientfd函数只有在客户机和服务器位于同一主机上时才能工作。
我说的对吗?我哪儿不好?
发布于 2021-05-05 14:12:31
你对host和port的意义的理解是不正确的。
服务器运行特定主机和特定端口。因此,host和port的组合可以识别单个服务器。
Getaddrinfo返回要尝试的(ip、端口)组合的列表,如果需要,可以使用DNS将主机名转换为IP地址列表。然后,函数尝试一个接一个地将它们连接起来,直到成功为止。
不管服务器在哪里运行,它都能工作。
https://stackoverflow.com/questions/67402638
复制相似问题