q0987
q0987

Reputation: 35982

When inet_pton fails but getaddrinfo succeeds?

In a legacy code base, I saw the following workflow.

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(i.e. sockaddr_in::sin_addr::s_addr).

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

Upvotes: 0

Views: 806

Answers (2)

John Bollinger
John Bollinger

Reputation: 180181

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

inet_pton() converts an IP address expressed in string form to an address structure.

getaddrinfo() can do the same (as also gethostbyname() can do), but it can also look up a host name to get an address, and fill the address info structure with the result. getaddrinfo() does some other work too.

Thus, inet_pton() will fail if you give it a string expressing a hostname, say "stackoverflow.com", but gethostbyname() may well succeed for such an input.

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

This sounds like it was intended to allow machines to be specified either by IP address or by name, by someone who did not appreciate that getaddrinfo() could handle both. The call to getaddrinfo() might have been a call to gethostbyname() in some earlier version of the software, which would have explained such a confusion better.

Or possibly the idea was to optimize the path where the machine is identified by an IP number, on the assumption that inet_pton() was substantially cheaper than getaddrinfo().

Either way, I would be inclined to instead just go straight to getaddrinfo(), without trying inet_pton().

Upvotes: 2

From man 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.

It's easy to see when inet_pton could possibly fail, whereas getaddrinfo has a lot more, 'fine-grained' (negative) return values (see man getaddrinfo).

getaddrinfo is just a more convenient way to retrieve a socket address.

From the man page of 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.

Upvotes: 0

Related Questions