How to convert string to IP address and vice versa

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

    inet_ntoa() converts a in_addr to string:

    The inet_ntoa function converts an (Ipv4) Internet network address into an ASCII string in Internet standard dotted-decimal format.

    inet_addr() does the reverse job

    The inet_addr function converts a string containing an IPv4 dotted-decimal address into a proper address for the IN_ADDR structure

    PS this the first result googling "in_addr to string"!

    0 讨论(0)
  • 2020-11-28 20:49

    The third inet_pton parameter is a pointer to an in_addr structure. After a successful inet_pton call, the in_addr structure will be populated with the address information. The structure's S_addr field contains the IP address in network byte order (reverse order).

    Example : 
    
    #include <arpa/inet.h>
    uint32_t NodeIpAddress::getIPv4AddressInteger(std::string IPv4Address) {
        int result;
        uint32_t IPv4Identifier = 0;
        struct in_addr addr;
        // store this IP address in sa:
        result = inet_pton(AF_INET, IPv4Address.c_str(), &(addr));
        if (result == -1) {         
    gpLogFile->Write(LOGPREFIX, LogFile::LOGLEVEL_ERROR, _T("Failed to convert IP %hs to IPv4 Address. Due to invalid family of %d. WSA Error of %d"), IPv4Address.c_str(), AF_INET, result);
        }
        else if (result == 0) {
            gpLogFile->Write(LOGPREFIX, LogFile::LOGLEVEL_ERROR, _T("Failed to convert IP %hs to IPv4"), IPv4Address.c_str());
        }
        else {
            IPv4Identifier = ntohl(*((uint32_t *)&(addr)));
        }
        return IPv4Identifier;
    }
    
    0 讨论(0)
  • 2020-11-28 20:49

    Hexadecimal IP Address to String IP

    #include <iostream>
    #include <sstream>
    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

    0 讨论(0)
提交回复
热议问题