当 inet_pton 失败但 getaddrinfo 成功时?

When inet_pton fails but getaddrinfo succeeds?

在遗留代码库中,我看到了以下工作流程。

给定 host(即 const char*),第一步是使用 inet_ptonhost 转换为 ip(即 uint32_t).如果失败,它会处理第二步,即使用 getaddrinfo 检索 ip(即 sockaddr_in::sin_addr::s_addr)。

问题> 谁能给我一个 inet_pton 失败(即 return != 1)而 getaddrinfo 成功的例子?

来自男人 inet_pton:

RETURN VALUE

inet_pton() returns 1 on success (network address was successfully converted). 0 is returned if src does not contain a character string representing a valid network address in the specified address family. If af does not contain a valid address family, -1 is returned and errno is set to EAFNOSUPPORT.

很容易看出 inet_pton 何时可能会失败,而 getaddrinfo 有更多,'fine-grained'(负)return 值(参见 man getaddrinfo)。

getaddrinfo 只是一种更方便的检索套接字地址的方法。

来自 getaddrinfo 的手册页:

DESCRIPTION

...
The getaddrinfo() function combines the functionality provided by the gethostbyname(3) and getservbyname(3) functions into a single interface, but unlike the latter functions, getaddrinfo() is reentrant and allows programs to eliminate IPv4-versus-IPv6 dependencies.

Can someone give me one example where the inet_pton fails(i.e. return != 1) while getaddrinfo succeeds?

inet_pton()将以字符串形式表示的IP地址转换为地址结构。

getaddrinfo() 可以做同样的事情(gethostbyname() 也可以),但它也可以查找主机 name 来获取地址,并用结果填充地址信息结构。 getaddrinfo() 也做一些其他工作。

因此,如果您给 inet_pton() 一个表示主机名的字符串,例如 "whosebug.com"inet_pton() 将失败,但是 gethostbyname() 很可能会成功。

Given a host(i.e const char*), step one is to use inet_pton to convert host to ip(i.e. uint32_t). In the case of failure, it processes step two which is to use getaddrinfo to retrieve the ip

这听起来好像是为了让机器可以通过 IP 地址或名称来指定,而有些人并不认为 getaddrinfo() 可以同时处理这两种情况。在该软件的某些早期版本中,对 getaddrinfo() 的调用可能是对 gethostbyname() 的调用,这可以更好地解释这种混淆。

或者可能的想法是优化由 IP 号识别机器的路径,假设 inet_pton()getaddrinfo() 便宜得多。

无论哪种方式,我都倾向于直接进入 getaddrinfo(),而无需尝试 inet_pton()