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

前端 未结 17 2103
悲哀的现实
悲哀的现实 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:02

    Boost.Asio provides the class ip::address. If you just want to verify the string, you can use it like this:

    std::string ipAddress = "127.0.0.1";
    boost::system::error_code ec;
    boost::asio::ip::address::from_string( ipAddress, ec );
    if ( ec )
        std::cerr << ec.message( ) << std::endl;
    

    This also works for hexadecimal and octal quads. This is also a much more portable solution.

提交回复
热议问题