gethostbyname 是否保证返回带有 IPv4 地址的主机结构?
我无法使用 getaddrinfo(...)
来解析主机名,因此必须坚持使用 gethostbyname(...)
是 gethostbyname(...)
code> 函数保证在成功时返回仅包含 IPv4 (AF_INET) 地址的 hostent 结构,因此以下代码始终会生成 IPv4 地址:
int resolve(const char *name, struct in_addr *addr) {
struct hostent *he = gethostbyname(name);
if (!he)
return 1;
memcpy(addr,he->h_addr_list[0],4);
return 0;
}
I cannot use getaddrinfo(...)
for resolving hostnames and therefore must stick to gethostbyname(...)
Is the gethostbyname(...)
function guaranteed to return hostent structures that contain only IPv4 (AF_INET) addresses on success, so that the following code would always lead to an IPv4 address:
int resolve(const char *name, struct in_addr *addr) {
struct hostent *he = gethostbyname(name);
if (!he)
return 1;
memcpy(addr,he->h_addr_list[0],4);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,
gethostbyname()
可以返回 IPV4(标准点)或 IPV6(标准冒号,或者点)表示法,至少在 Linux 上。你需要处理这个问题。我认为它的各种实现仅返回 IPV4(例如 PHP),但每个我使用过的 C 平台可以并且将会返回两者。如果您的应用程序仅支持 IPV4,那么如果用户没有合适的接口来连接到远程主机,那么很容易发现您正在处理 IPV6 并出错。即使您的应用同时支持两者,用户的网关支持什么?
超过三个
.
或存在:
.. 其 IPV6。编辑
h_addr
是h_addrlist_[0]
的同义词,而h_length
是所有地址的长度。也许我没有充分理解你的问题?
No,
gethostbyname()
can return IPV4 (standard dot) or IPV6 (standard colon, or perhaps dot) notation, at least on Linux. You'll need to deal with that. I think various implementations of it return only IPV4 (e.g PHP), but every C platform that I've used can and will return both.If your app is IPV4 only, its not too difficult to figure out that you are dealing with IPV6 and error out if the user does not have a suitable interface to connect to the remote host. Even if your app supports both, what does the user's gateway support?
More than three
.
or the presence of:
.. its IPV6.Edit
h_addr
is a synonym forh_addrlist_[0]
, whileh_length
is the length of all addresses.Perhaps I'm not adequately understanding your question?
h_addrtype 告诉您 h_addr_list 是否包含 IPv4、IPv6 或其他类型的地址。您可以使用开关来更改该行: memcpy(addr,he->h_addr_list[0],4); to memcpy(addr,he->h_addr_list[0],N);其中 N 是地址类型所需的长度。根据 MSDN 文档,h_length 是“每个”地址的长度。
h_addrtype tells you if h_addr_list contains IPv4 or IPv6 or other types of addresses. You can use a switch to change the line: memcpy(addr,he->h_addr_list[0],4); to memcpy(addr,he->h_addr_list[0],N); where N is the required length for the address type. Per MSDN documentation, h_length is the length of 'each' address.