Chinaunix首页 | 论坛 | 博客
  • 博客访问: 243866
  • 博文数量: 62
  • 博客积分: 973
  • 博客等级: 准尉
  • 技术积分: 530
  • 用 户 组: 普通用户
  • 注册时间: 2011-11-16 23:25
文章分类

全部博文(62)

文章存档

2013年(1)

2012年(14)

2011年(47)

分类: C/C++

2011-12-31 16:10:28

  1. /**
  2.  * reference: bash-4.1/lib/sh/inet_aton.c
  3.  * Convert an Internet Address to a numeric address.
  4.  * Support base 8(prefix 0..),10,16(prefix 0x..)
  5.  * Returns 1 if the IP is valid, 0 if not.
  6. */
  7. int ipton(const char *cp, unsigned long int *addr_u)
  8. {
  9.     int base;
  10.     unsigned long int val;
  11.     unsigned char c;
  12.     unsigned int fields[4];
  13.     unsigned int *pfield = fields;
  14.     
  15.     c = *cp;
  16.     while( c )
  17.     {
  18.         if( !isdigit(c) )
  19.             return 0;
  20.         val = 0;
  21.         // deal with base
  22.         base = 10;
  23.         if('0' == c)
  24.         {
  25.             c = *(++cp);
  26.             if('x' == c || 'X' == c)
  27.             {
  28.                 base = 16;
  29.                 c = *++cp;
  30.             }
  31.             else
  32.                 base = 8;
  33.         }
  34.         //calculate 4 parts
  35.         for(;;)
  36.         {
  37.             if( isascii(c) && isdigit(c) )
  38.             {
  39.                 val = (val * base) + (c - '0');
  40.                 c = *(++cp);
  41.             }
  42.             else if( (16 == base) && isascii(c) && isxdigit(c) )
  43.             {
  44.                 c |= 0x20; /* tolower */
  45.                 val = (val << 4) | (c + 10 - 'a');
  46.                 c = *++cp;
  47.             } else
  48.                 break;
  49.         }
  50.         if(val > 0xff) //max is 255
  51.             return 0;
  52.         if('.' == c)
  53.         {
  54.         // 15.25.35.45, the 3d '.', pfield point to 3
  55.             if (pfield >= fields + 3)
  56.                 return 0;
  57.             *pfield++ = val;
  58.             c = *++cp;
  59.             printf("%ld\t", val);
  60.         } else
  61.             break;
  62.     }
  63.     if( c != '\0' && ( !isascii(c) || !isspace(c) ) )
  64.         return 0;
  65.     if( pfield - fields +1 < 4 )
  66.         return 0;
  67.     printf("%ld is:\n", val);
  68.     val |= (fields[0] << 24) | (fields[1] << 16) | (fields[2] << 8 );
  69.     *addr_u = val;

  70.     return 1;
  71. }

  72. int main(void)
  73. {
  74.     unsigned long int fromip;
  75.     if( ipton("0xF8.248.0365.245 ", &fromip) > 0 )
  76.         printf("%ul\n", fromip);

  77.     return 0;
  78. }
阅读(1550) | 评论(0) | 转发(0) |
0

上一篇:寻找丑数

下一篇:C++常用库

给主人留下些什么吧!~~