Efficient way to store IPv4 / IPv6 addresses

I am working on a C / C ++ network project so that it can use the IPv4 and IPv6 network stacks. The project only works on Linux. So, I tried to find an efficient way to store IP addresses and distinguish between protocol families. The first approach was to combine:

struct ip_addr { uint8_t fam; // socket family type union { struct in_addr ipv4_sin_addr; struct in6_addr ipv6_sin_addr; }addr; }; 

The second approach was to define a typedef std::vector<unsigned char> IPAddressNumber and change the value after the number of bytes from the vector.

The third approach was to use int128_t / uint128_t or __int128_t from gcc.

In this latter case, I would like to know from which version of GCC these types are supported, for which platforms (especially IA-32 / IA-64), and also if there are any known errors. In addition, which of the above solutions may be the most convenient?

+7
c ++ gcc ipv4 ipv6 int128
source share
2 answers

As indicated in the 1st answer Support for a 128-bit integer is available with GCC 4.6.4.

Your problem is not 128-bit integer support, but how to correctly represent the IPv6 address .
The correct answer for this is to use struct definitions available from the socket APIs .

They are available and standardized for various versions of the IPv6 stack operating system.
Also, you do not need to worry about efficiency with their help. Alignment packaging will work correctly, and you don’t need to worry about problems with the serial number in the line “endianess vs network byte” of the actual view.


Regarding your rights:

You do not need to reinvent the wheel! . The corresponding struct definitions available for the AF_xxx family of families AF_xxx already correct.

Check out these resources for more detailed explanations:

We have an IpAddr class that uses the opaque pointers sockaddr_in* and sockaddr_in6* to encapsulate an IPv4 or IPv6 address based on the sockaddr* pointer and reinterpret_cast<> based on the sa_family member of the structure.

+9
source share

According to this stream, __int128_t and __uint128_t were introduced somewhere around version 4.2. And according to the GCC documentation __int128 and its unsigned counterpart unsigned __int128 supported with GCC 4.6.4 .

Note that the unportable 128-bit integer is definitely not the appropriate type for saving and working with IPv6 addresses. As mentioned in the comments, there are special data structures for this, such as sockaddr_in6 .

+3
source share

All Articles