How to convert string to IP address and vice versa

前端 未结 9 776
傲寒
傲寒 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:49

    Hexadecimal IP Address to String IP

    #include 
    #include 
    using namespace std;
    
    int main()
    {
        uint32_t ip = 0x0AA40001;
        string ip_str="";
        int temp = 0;
        for (int i = 0; i < 8; i++){
            if (i % 2 == 0)
            {
                temp += ip & 15;
                ip = ip >> 4;
            }
            else
            {
                stringstream ss;
                temp += (ip & 15) * 16;
                ip = ip >> 4;
                ss << temp;
                ip_str = ss.str()+"." + ip_str;
                temp = 0;
            }
        }
        ip_str.pop_back();
        cout << ip_str;
    }
    

    Output:10.164.0.1

提交回复
热议问题