Efficient way to store IPv4/IPv6 addresses

前端 未结 3 1633
春和景丽
春和景丽 2021-01-12 06:27

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 e

3条回答
  •  花落未央
    2021-01-12 06:57

    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.

提交回复
热议问题