here are the easy-to-use, thread-oriented c ++ functions for converting uint32_t native-endian to string and string to native-endian uint32_t:
#include <arpa/inet.h> // inet_ntop & inet_pton #include <string.h> // strerror_r #include <arpa/inet.h> // ntohl & htonl using namespace std; // im lazy string ipv4_int_to_string(uint32_t in, bool *const success = nullptr) { string ret(INET_ADDRSTRLEN, '\0'); in = htonl(in); const bool _success = (NULL != inet_ntop(AF_INET, &in, &ret[0], ret.size())); if (success) { *success = _success; } if (_success) { ret.pop_back(); // remove null-terminator required by inet_ntop } else if (!success) { char buf[200] = {0}; strerror_r(errno, buf, sizeof(buf)); throw std::runtime_error(string("error converting ipv4 int to string ") + to_string(errno) + string(": ") + string(buf)); } return ret; } // return is native-endian // when an error occurs: if success ptr is given, it set to false, otherwise a std::runtime_error is thrown. uint32_t ipv4_string_to_int(const string &in, bool *const success = nullptr) { uint32_t ret; const bool _success = (1 == inet_pton(AF_INET, in.c_str(), &ret)); ret = ntohl(ret); if (success) { *success = _success; } else if (!_success) { char buf[200] = {0}; strerror_r(errno, buf, sizeof(buf)); throw std::runtime_error(string("error converting ipv4 string to int ") + to_string(errno) + string(": ") + string(buf)); } return ret; }
honest warning, at the time of writing, they are not verified. but these functions are exactly what I was looking for when I came to this thread.
hanshenrik Jan 22 '19 at 18:39 2019-01-22 18:39
source share