Skip to content

Instantly share code, notes, and snippets.

@alphamarket
Last active March 8, 2020 06:05
Show Gist options
  • Save alphamarket/5a3c653807ed1bf95625f24ea29154e7 to your computer and use it in GitHub Desktop.
Save alphamarket/5a3c653807ed1bf95625f24ea29154e7 to your computer and use it in GitHub Desktop.
Converts IPv4 and IPv6 to decimal (long value) in C++
#include <iostream>
#include <boost/asio/ip/address.hpp>
#include <boost/multiprecision/cpp_int.hpp>
using big_int = boost::multiprecision::cpp_int;
big_int ip2long(const std::string&);
int main(int, char**) {
const auto
fals = "xxx.xxx.x.x",
ipv4 = "192.168.1.1",
ipv6 = "2001:4860:4860::8888";
const auto
fals_dec = ip2long(fals),
ipv4_dec = ip2long(ipv4),
ipv6_dec = ip2long(ipv6);
std::cout
<< "FALSE: " << fals << " -> " << fals_dec << std::endl
<< " IPv4: " << ipv4 << " -> " << ipv4_dec << std::endl
<< " IPv6: " << ipv6 << " -> " << ipv6_dec << std::endl;
/**
output:
FALSE: xxx.xxx.x.x -> 0
IPv4: 192.168.1.1 -> 3232235777
IPv6: 2001:4860:4860::8888 -> 42541956123769884636017138956568135816
ref:
IPv4: https://www.ipaddressguide.com/ip
IPv6: https://www.ipaddressguide.com/ipv6-to-decimal
**/
return EXIT_SUCCESS;
}
/**
* @brief ip2long converts IP to long value
* @param ip_addr the input IP (IPv4 or IPv6)
* @return cpp_int as the IP's long value
* @author Dariush Hasanpour <b.g.dariush@gmail.com>
*/
big_int ip2long(const std::string& ip_addr) {
// the output's default value
big_int decimal = 0;
// try to compute the decimal value of the input
try {
// convert the string IP into the boost IP object
auto addr = boost::asio::ip::make_address(ip_addr);
// check if the IP is v4 type
if (addr.is_v4()) {
// just convert it to `uint` as it's decimal
decimal = addr.to_v4().to_uint();
// check if the IP is v6 type
} else if (addr.is_v6()) {
// get the v6's bytes
auto bytes = addr.to_v6().to_bytes();
// compute the decimal value from the array of hexa-decimal values
for (int i = 0; i < sizeof(bytes); i++)
decimal = (decimal << 0x8) | bytes[i];
}
} catch(...) { /* ignore if anything raises */ }
// return decimal value of the input IP
return decimal;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment