Is there a clever/tricky way to analyze if a string represented IP address is valid and to recognize its version, so that to be able to convert it to the appropriate structure, just by using the UNIX API?
I don't want to use regex, no need to add dependency to additional libraries just about this.
My first approach was:
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 here is, that if I pass string like 1, it's successfully converted to IPv4. String like 11111 is converted to IPv4, too. By documentation:
inet_aton() returns non-zero if the address is valid, zero if not.
Obviously, this function recognizes not only XXX.XXX.XXX.XXX format, but does something more internally.
Of course I can write my own function(and it's going to be fun, actually), by analyzing the string, but I wanted to use already existing and tested functions, instead. Is it possible or I should write my own?