Maybe using scanf with "%2hhX.%2hhX.%2hhX.%2hhX"? Example:
Code:
#include <stdlib.h>
#include <stdio.h>
int main( void )
{
unsigned char a[4];
int converted;
const static char ipstr[] = "AA.0.CC.DD"; // should pass.
const static char ipstr2[] = "AA.256.0.10"; // should fail.
if ( ( converted = sscanf( ipstr, "%2hhX.%2hhX.%2hhX.%2hhX", a, a+1, a+2, a+3 ) ) != 4)
{
if ( converted == EOF )
perror( "sscanf" );
else
fprintf( stderr, "error: Only %d octects converted.\n", converted );
return EXIT_FAILURE;
}
printf("%hhu.%hhu.%hhu.%hhu\n", *a, *(a+1), *(a+2), *(a+3));
if ( ( converted = sscanf( ipstr2, "%2hhX.%2hhX.%2hhX.%2hhX", a, a+1, a+2, a+3 ) ) != 4)
{
if ( converted == EOF )
perror( "sscanf" );
else
fprintf( stderr, "error: Only %d octects converted.\n", converted );
return EXIT_FAILURE;
}
printf("%hhu.%hhu.%hhu.%hhu\n", *a, *(a+1), *(a+2), *(a+3));
return EXIT_SUCCESS;
}
There is also inet_pton(), but it fails with non standard IPv4 or IPv6 addresses...