Efficient way to store IPv4/IPv6 addresses

北慕城南 提交于 2019-12-01 16:54:12
πάντα ῥεῖ

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:

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.

Columbo

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!