How to convert string to IP address and vice versa

前端 未结 9 779
傲寒
傲寒 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

    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 
    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;
    }
    

提交回复
热议问题