112

Read an IP address

  1. #include <ctype.h>
  2.  
  3. int atoip( unsigned char *v4, const char *in ) {
  4.     unsigned char *pv4;
  5.     const char *cp;
  6.     char c;
  7.  
  8.     int val;
  9.  
  10.     cp = in;
  11.     pv4 = v4;
  12.  
  13.     while ( pv4 < v4 + 4 ) {
  14.         val = 0;
  15.         while ( (c = *cp) != '\0' ) {
  16.             if ( !isdigit( (unsigned char) c ) )
  17.                 break;
  18.             val = val * 10 + (c - '0');
  19.             cp++;
  20.         }
  21.         if ( val < 0 || val > 255 )
  22.             return 0;
  23.         *pv4++ = val;
  24.         if ( *cp != '.' )
  25.             break;
  26.         cp++;
  27.     }
  28.  
  29.     if ( *cp != '\0' )
  30.         return 0;
  31.  
  32.     if ( pv4 - v4 != 4 )
  33.         return 0;
  34.  
  35.     return 1;
  36. }
  37.  
  38. #if defined( STANDALONE )
  39.  
  40. #include <stdio.h>
  41.  
  42. int main( int argc, char *argv[] ) {
  43.     unsigned char v4[4];
  44.  
  45.     if (argc == 2) {
  46.         if  (atoip(v4, argv[1])) {
  47.             fprintf( stdout, "%d.%d.%d.%d\n", v4[0], v4[1], v4[2], v4[3]);
  48.             return 0;
  49.         }
  50.         fprintf( stderr, "%s?\n", argv[1] );
  51.     }
  52.     else
  53.         fprintf( stderr, "%s ipaddr\n", argv[0] );
  54.  
  55.     return 1;
  56. }
  57.  
  58. #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

Your comment:
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip help 2000

Enter a maximum of 2000 characters.
Improve the presentation of your text with the following formatting tags:
[p]paragraph[/p], [b]bold[/b], [i]italics[/i], [u]underline[/u], [s]strike[/s], [quote]citation[/quote], [pre]as is[/pre], [br]line break,
[url]http://www.izend.org[/url], [url=http://www.izend.org]site[/url], [email]izend@izend.org[/email], [email=izend@izend.org]izend[/email],
[code]command[/code], [code=language]source code in c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].