IP字符串数字互转

封装的IP字符串与数字互转接口

一、字符串转数字

text
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*
@func: IP字符串形式转换成数字形式,支持IPV6
@note: IP字符串中包含':'则认为是IPV6
IPV4返回值保存到 ip_num_low , IPV6返回值保存到 ip_num_high+ip_num_low
*/
struct IPNum
{
   int is_ipv6;
   uint64_t ip_num_low;
   uint64_t ip_num_high;
   IPNum()
  {
       is_ipv6 = 0;
       ip_num_low = 0;
       ip_num_high = 0;
  }
};

int ip2num(const std::string &ip_str, IPNum &ip_num)
{
   if(ip_str.find(':') != std::string::npos)
  {
       struct in6_addr ipv6{};
       inet_pton(AF_INET6, ip_str.c_str(), &ipv6);
       ip_num.ip_num_low = ipv6.s6_addr32[2];
       ip_num.ip_num_low = ipv6.s6_addr32[3] | (ip_num.ip_num_low << 32);
       ip_num.ip_num_high = ipv6.s6_addr32[0];
       ip_num.ip_num_high = ipv6.s6_addr32[1] | (ip_num.ip_num_high << 32);
       ip_num.is_ipv6 = 1;
  }
   else
  {
       ip_num.ip_num_low = inet_addr(ip_str.c_str());
  }
   return 0;
}

二、数字转字符串

待续。。。