문제

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;
}
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top