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

前端 未结 17 2091
悲哀的现实
悲哀的现实 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-05 00:07

    void validate_ip_address(const std::string& s) {
        const std::string number_0_255 = "((([0-9])|([1-9][0-9])|(1[0-9][0-9]|2[0-4][0-9]|25[0-5])){1})";
        const std::string dot = "(\\.){1}";
        static const boost::regex e(number_0_255 + dot + number_0_255 + dot + number_0_255 + dot + number_0_255);
        if (!regex_match(s, e)) {
            throw std::runtime_error(std::string("Uncorrect address IP: ") + s);
        }
    }
    

提交回复
热议问题