How do you validate that a string is a valid IPv4 address in C++?

前端 未结 17 2063
悲哀的现实
悲哀的现实 2020-12-04 23:21

I don\'t need to validate that the IP address is reachable or anything like that. I just want to validate that the string is in dotted-quad (xxx.xxx.xxx.xxx) IPv4 format, w

17条回答
  •  抹茶落季
    2020-12-04 23:58

    If you wish to receive an IP address in the usual form (8.8.8.8, 192.168.1.1, etc...) Then I've written the following code that expands on Bjorn's answer:

    void validateIP(const std::string &IPv4_address)
    {
        boost::system::error_code error_code;
        auto raw_ipv4_address = boost::asio::ip::address::from_string(IPv4_address, error_code);
        if (error_code)
        {
            throw std::invalid_argument(error_code.message());
        }
    
        std::string raw_to_string_form = raw_ipv4_address.to_string();
        if (raw_to_string_form.compare(IPv4_address))
        {
            throw std::invalid_argument("Input IPv4 address is invalid");
        }
    }
    

    The reason being is that if you pass on an IP such as 8.88.8, or 12345 (decimal form), Bjorn's answer won't throw an error. (at least with boost 1.68) My code converts any form to the internal structure in Boost, then converts it back to a dotted-decimal format, we then compare it to the first IP we received to see if they are equal, if not, we know for sure that the input is not the way we wanted it.

提交回复
热议问题