了解 CSAPP 书中的代码 open_clientfd(char *hostname, char *port)? :参数主机名和端口的问题
Understanding code open_clientfd(char *hostname, char *port) from book CSAPP? : issue for argument hostname and port
在看这本书和网络编程一章的时候,看到了一个这样的函数:
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 函数在主机 hostname 上与服务器 运行 建立连接,并在端口号 port 上侦听连接请求。”
因此,我了解到在客户端-服务器事务中,主机名用于客户端,端口用于服务器。
我的疑问来自代码,Getaddrinfo(hostname, port, &hints, &listp);
由于 getaddrinfo 的主机和服务参数是套接字地址的两个组成部分(如书上所说),我认为此 open_clientfd 函数仅在客户端和服务器位于同一主机上时才有效。
我说的对吗?
我怎么了?
您对host
和port
意义的理解不正确。
服务器运行特定主机和特定端口。因此 host
和 port
的组合标识单个服务器。
Getaddrinfo
returns 要尝试的(ip、端口)组合列表,如果需要,使用 DNS 将主机名转换为 IP 地址列表。该函数然后尝试将它们一一连接,直到一个成功。
无论服务器在哪里运行,它都可以正常工作。
在看
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 函数在主机 hostname 上与服务器 运行 建立连接,并在端口号 port 上侦听连接请求。”
因此,我了解到在客户端-服务器事务中,主机名用于客户端,端口用于服务器。
我的疑问来自代码,Getaddrinfo(hostname, port, &hints, &listp);
由于 getaddrinfo 的主机和服务参数是套接字地址的两个组成部分(如书上所说),我认为此 open_clientfd 函数仅在客户端和服务器位于同一主机上时才有效。
我说的对吗? 我怎么了?
您对host
和port
意义的理解不正确。
服务器运行特定主机和特定端口。因此 host
和 port
的组合标识单个服务器。
Getaddrinfo
returns 要尝试的(ip、端口)组合列表,如果需要,使用 DNS 将主机名转换为 IP 地址列表。该函数然后尝试将它们一一连接,直到一个成功。
无论服务器在哪里运行,它都可以正常工作。