views:

23

answers:

1

I used to think the second argument for inet_ntop should always be a struct in_addr or struct in6_addr. But then I looked up the POSIX definition:

const char *inet_ntop(int af, const void *restrict src,
                      char *restrict dst, socklen_t size);

[...] The src argument points to a buffer holding an IPv4 address if the af argument is AF_INET, or an IPv6 address if the af argument is AF_INET6; the address must be in network byte order. [...]

As you can see both the function prototype and the description are vague.

Why is this? And what are allowed/portable choices for src?

+1  A: 

It's a pointer to an IPv4 or IPv6 as stored in the respective headers - so a 4 byte buffer in the case of IPv4, and a 16 byte buffer in the case of IPv6.

struct in_addr and struct in6_addr are convenient structures for storing such addresses, but you could use unsigned char [4] and unsigned char [16] respectively, if you wanted.

caf
In that case, `struct in_addr` or `struct in6_addr` would only work if the IP address is the first member. Is this a POSIX requirement? I could not find a reference for this.
schot
@schot: That's a good point - I suppose that technically means you need to pass the address of the `s_addr` and/or `s6_addr` members of those structs.
caf
Thanks for your answer, I will use `in_addr_t ` and `uint8_t [16]`, the types of the `s(6)_addr` members.
schot