Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is INET6_ADDRSTRLEN defined as 46 in C?

Tags:

c

sockets

ipv6

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?

like image 338
Lone Learner Avatar asked Sep 12 '16 04:09

Lone Learner


People also ask

What is the maximum length of IPv6 address?

IPv6 uses 128-bit (2128) addresses, allowing 3.4 x 1038 unique IP addresses. This is equal to 340 trillion trillion trillion IP addresses. IPv6 is written in hexadecimal notation, separated into 8 groups of 16 bits by the colons, thus (8 x 16 = 128) bits in total.

What is Inet_addrstrlen?

h>: in wsipdef. h, INET_ADDRSTRLEN is 22 and INET6_ADDRSTRLEN is 65. This accommodates for optional brackets around the IPv6 address with scope ID, a colon and a port number. For example: [ffff:ffff:ffff:ffff:ffff:ffff:255.255.

How many characters does IPv6 have?

In hexadecimal, 4 bits (also known as ”nibble”) are represented by a digit or character from 0-9 and a-f (10-15). This format reduces the length of the IPv6 address to 32 characters.


Video Answer


2 Answers

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.

like image 161
P.P Avatar answered Oct 21 '22 17:10

P.P


It's probably for the IPv4-mapped form of addresses of the form:

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

Read more:

Wireshark-dev mailing list

RFC 4291 section 2.2

like image 41
e.dan Avatar answered Oct 21 '22 17:10

e.dan