137
Read an IP address
- #include <ctype.h>
- int atoip( unsigned char *v4, const char *in ) {
- unsigned char *pv4;
- const char *cp;
- char c;
- int val;
- cp = in;
- pv4 = v4;
- while ( pv4 < v4 + 4 ) {
- val = 0;
- while ( (c = *cp) != '\0' ) {
- if ( !isdigit( (unsigned char) c ) )
- break;
- val = val * 10 + (c - '0');
- cp++;
- }
- if ( val < 0 || val > 255 )
- return 0;
- *pv4++ = val;
- if ( *cp != '.' )
- break;
- cp++;
- }
- if ( *cp != '\0' )
- return 0;
- if ( pv4 - v4 != 4 )
- return 0;
- return 1;
- }
- #if defined( STANDALONE )
- #include <stdio.h>
- int main( int argc, char *argv[] ) {
- unsigned char v4[4];
- if (argc == 2) {
- if (atoip(v4, argv[1])) {
- fprintf( stdout, "%d.%d.%d.%d\n", v4[0], v4[1], v4[2], v4[3]);
- return 0;
- }
- fprintf( stderr, "%s?\n", argv[1] );
- }
- else
- fprintf( stderr, "%s ipaddr\n", argv[0] );
- return 1;
- }
- #endif
$ gcc -DSTANDALONE -o atoip atoip.c
$ ./atoip
atoip ipaddr
$ ./atoip 192.168.1.23
192.168.1.23
$ ./atoip 192.168.1.1023
192.168.1.1023?
$ ./atoip 255.255.255.255
255.255.255.255
$ ./atoip 0.0.0.0
0.0.0.0
$ ./atoip 127...1
127.0.0.1
Comments