Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to store IPv4/IPv6 addresses

I am working on a C/C++ networking project that it should be able to both use the IPv4 and IPv6 networking stacks. The project works only on Linux. So, I tried to find an efficient way to store the IP addresses and differentiate between the protocol families. The first approach was to have a union:

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 IPAddressNumber`and make the difference after the number of bytes from the vector.

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

For this last 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 bugs. Also, which of the above solutions might be the most convenient one?

like image 263
evelina Avatar asked Oct 23 '14 15:10

evelina


2 Answers

As stated in the 1st answer 128 bit integer support is available since GCC 4.6.4.

Your problem isn't 128 bit integer support, but how to represent an IPv6 address correctly.
The correct answer for this, is to use the struct definitions available from the socket API.

These are available and standardized for various operating system implementations of the IPv6 stack.
Also you don't need to worry about efficiency using these. Alignment packing will do its work properly, and you don't have to care about endianess vs network byte order issues of the actual representation.


As for your edits:

You don't have to reinvent the wheel! There are already appropriate struct definitions available respecting the AF_xxx family type correctly.

Check these resources for more detailed explanations:

  • Understanding struct sockaddr.
  • sys/socket.h - main sockets header
  • netinet/in.h - Internet address family

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

like image 123
πάντα ῥεῖ Avatar answered Sep 23 '22 13:09

πάντα ῥεῖ


According to this thread __int128_t and __uint128_t were introduced somewhere around version 4.2. And according to GCC's documentation __int128 and its unsigned counterpart unsigned __int128 are supported since GCC 4.6.4.

Note that an unportable 128-bit integer is definitely not the appropriate type to save and work with IPv6 addresses. As mentioned in the comments there are special data structures for this, like sockaddr_in6.

like image 36
Columbo Avatar answered Sep 19 '22 13:09

Columbo