The following program and its output shows that INET_ADDRSTRLEN
is defined as 16
and INET6_ADDRSTRLEN
is defined as 46
.
Here is the program.
#include <stdio.h>
#include <arpa/inet.h>
int main()
{
printf("%d\n", INET_ADDRSTRLEN);
printf("%d\n", INET6_ADDRSTRLEN);
return 0;
}
Here is the output.
16
46
I can understand why INET_ADDRSTRLEN
needs to be 16
. The largest possible string representation of an IPv4 address consumes 15 bytes, e.g. "255.255.255.255"
. Therefore 16 bytes are required to store such an IP address with its terminating null character.
But why does INET6_ADDRSTRLEN
need to be 46
? The largest possible string representation of an IPv6 address consumes only 39 bytes (according to my knowledge), e.g. "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"
. Therefore only 40 bytes are required to store such an IP address with its terminating null character.
Is there a string representation of an IPv6 address that can consume 46 bytes?
Why is INET6_ADDRSTRLEN defined as 46 in C?
Because POSIX defines it to be 46:
INET6_ADDRSTRLEN
46. Length of the string form for IPv6.
While you are right that longtest IPv6 address takes 39 bytes, with IPv4 tunneling, the longest form can be 45 bytes:
ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255
And the 46th byte is for the terminating nul byte (in C a string). This explains how it came to be 46.