views:

129

answers:

1

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;
}
+2  A: 

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?

Tim Post
So if the DNS resolver behind gethostbyname returns an IPv6 address my application shall fail?
Robert
@Robert - That's subjective. Can the _user_ of the application connect to an IPV6 address?
Tim Post
@Tim: it could also succeed because it's a program that checks a site for updates. But how large should my structures be then if I would also accept AF_INET6 !?
Robert
@Robert, if `h_addrtype` is `AF_INET6` or `AF_INET`, `h_length` reflects either. I'm not sure I understand your question?
Tim Post
@Robert, are you sure you don't want `gethostbyname2()` ?
Tim Post
@Tim: gethostbyname2() would be perfect if it would not create the same dependence as getaddrinfo(). It's therefore not suitable for my problem.
Robert
@Robert - Roll your own. Can you describe your platform and restrictions?
Tim Post
Linux only, static binary, get this warning: 'warning: Using 'getaddrinfo' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking' - any ideas?
Robert