问题
I need to convert IPv6 string address into boost::multiprecision::uint128_t For IPv4 I used the following algorithm:
uint32_t byte1 = 0, byte2 = 0, byte3 = 0, byte4 = 0;
sscanf(ipAddress, "%3d.%3d.%3d.%3d", &byte1, &byte2, &byte3, &byte4);
uint32_t ip = (byte1 << 24) | (byte2 << 16) | (byte3 << 8) | (byte4);
How can I do like this for IPv6?
回答1:
Using the example from Wikipedia:
Also using Boost Asio's address_v6
implementation instead of a 1970-era parsing:
Live On Coliru
#include <boost/asio/ip/address_v6.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <cstdio>
using boost::asio::ip::address_v6;
using boost::multiprecision::int128_t;
int main() {
auto v6 = address_v6::from_string("2001:0DBB:AC10:FE01::");
int128_t val {};
for (uint8_t b : v6.to_bytes())
(val <<= 8) |= b;
std::cout << std::hex << std::showbase << val << std::endl;
}
Prints
0x20010dbbac10fe010000000000000000
来源:https://stackoverflow.com/questions/62005472/c-ipv6-string-representation-into-boostmultiprecisionuint128-t