Is there a smart / tricky way to parse if the string representing the IP address is valid and recognizes its version in order to be able to convert it to the appropriate structure simply using the UNIX API?
I do not want to use regular expression, I do not need to add dependencies to additional libraries.
My first approach:
in_addr addr; memset( &addr, 0, sizeof( in_addr ) ); // try to convert from standard numbers-and-dots notation into binary data if( 0 != inet_aton( sIPAddress.c_str(), &addr ) ) { return Socket::enIPv4; // valid IPv4 } in6_addr addr6; memset( &addr6, 0, sizeof( in6_addr ) ); if( inet_pton( AF_INET6, sIPAddress.c_str(), &addr6 ) > 0 ) { return Socket::enIPv6; // valid IPv6 } return Socket::enUnknown;
The problem is that if I pass the string as 1 , it is successfully converted to IPv4. String type 11111 also converted to IPv4. According to the documentation:
inet_aton () returns a non-zero value if the address is valid, zero if not.
Obviously, this function not only recognizes the format XXX.XXX.XXX.XXX , but also does something more internally.
Of course, I can write my own function (and it will be fun, actually) by analyzing the string, but instead I wanted to use existing and proven functions. Is this possible, or should I write my own?
source share