laurent
laurent

Reputation: 90736

How to represent an IPv6 in C++?

I'm wondering what would be the most efficient way to store an IPv6 in C++?

Basically I need a format that offer as much flexibility as possible, and compatibility with existing libraries. My first thought was to use a simple std::vector<int> since that would allow me to access each part of the address easily.

Is that a good solution? Or am I likely to run into troubles later on?

Upvotes: 1

Views: 1921

Answers (2)

David Mokon Bond
David Mokon Bond

Reputation: 1656

That should be fine but you might want to do a std::vector<uint8_t>. I would personally use the struct sockaddr_in6 from c.

/* IPv6 address */
struct in6_addr
  {
    union
      {
    uint8_t u6_addr8[16];
    uint16_t u6_addr16[8];
    uint32_t u6_addr32[4];
      } in6_u;
#define s6_addr         in6_u.u6_addr8
#define s6_addr16       in6_u.u6_addr16
#define s6_addr32       in6_u.u6_addr32
  };

Include this:

  #include <netinet/in.h>

That way you can just use static intilization of your address and be done with it. Doing repeated push_backs onto the vector would get very cumbersome and make it a lot harder to read.

Upvotes: 7

Paul Chan
Paul Chan

Reputation: 43

You mean to store an IPv6 address? If so, int is not enough, you need 128 bits for each.

Upvotes: 0

Related Questions