How to convert string to IP address and vice versa

前端 未结 9 763
傲寒
傲寒 2020-11-28 19:43

how can I convert a string ipAddress (struct in_addr) and vice versa? and how do I turn in unsigned long ipAddress? thanks

9条回答
  •  隐瞒了意图╮
    2020-11-28 20:41

    here's easy-to-use, thread-safe c++ functions to convert uint32_t native-endian to string, and string to native-endian uint32_t:

    #include  // inet_ntop & inet_pton
    #include  // strerror_r
    #include  // 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's 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;
    }
    

    fair warning, as of writing, they're un-tested. but these functions are exactly what i was looking for when i came to this thread.

提交回复
热议问题