开发者

Is gethostbyname guaranteed to return hostent structures with IPv4 addresses?

开发者 https://www.devze.com 2022-12-29 04:33 出处:网络
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

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 = g开发者_如何学编程ethostbyname(name);

    if (!he)
        return 1;

    memcpy(addr,he->h_addr_list[0],4);

    return 0;
}


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 for h_addrlist_[0], while h_length is the length of all addresses.

Perhaps I'm not adequately understanding your question?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消