Why is INET6_ADDRSTRLEN defined as 46 in C?

The following program and its output show that INET_ADDRSTRLEN is defined as 16 , and INET_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 result.

 16 46 

I can understand why INET_ADDRSTRLEN should be 16 . The largest possible string representation of an IPv4 address consumes 15 bytes, for example. "255.255.255.255" . Therefore, 16 bytes is required to store such an IP address with its null character.

But why should INET6_ADDRSTRLEN be 46 ? The maximum possible string representation of an IPv6 address consumes only 39 bytes (according to my knowledge), for example. "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff" . Therefore, only 40 bytes with its trailing null character are required to store such an IP address.

Is there a string representation of an IPv6 address that can consume 46 bytes?

+7
c sockets ipv6
source share
2 answers

Why is INET6_ADDRSTRLEN defined as 46 in C?

Because POSIX defines it as 46:

INET6_ADDRSTRLEN
46. ​​The length of the string form for IPv6.

As long as you are right that the longest IPv6 address is 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 intended to end the null byte (on line C). This explains how it became 46.

+19
source share

This is probably for an IPv4-mapped form address form:

 ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255 

More details:

Wireshark-dev mailing list

RFC 4291 Section 2.2

+3
source share

All Articles