Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1364486
  • 博文数量: 704
  • 博客积分: 10140
  • 博客等级: 上将
  • 技术积分: 6230
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-15 20:41
文章分类

全部博文(704)

文章存档

2013年(1)

2012年(16)

2011年(536)

2010年(151)

分类: C/C++

2010-10-06 19:36:16


ip地址以字符串的形式给出,现在要求写一段代码来验证此ip地址是否合法。

#include
#include
#include
#include
#include

/* define macro BOOL, FALSE, TRUE */
#ifndef BOOL
typedef int BOOL;
#define FALSE 0
#define TRUE 1
#endif    /* end of BOOL */

BOOL is_valid_ip_address(const char *addr);

int main(void)
{
    char *addr = "10a.193.174.124";
   
    if ( is_valid_ip_address(addr) )
    {
        printf("%s is a valid ip address.\n", addr);
    }
    else
    {
        printf("%s is a invalid ip address.\n", addr);
    }

    exit(EXIT_SUCCESS);
}

BOOL is_valid_ip_address(const char *addr)
{
    int num= 0;
    int i = 0, j = 0;
    int value;
    char buf[4] ;

    memset(buf, 0, sizeof(buf));
    while ( *(addr + i) != '\0' )
    {
        ++num;
        while ( *(addr + i) != '\0' && *(addr + i) != '.' )
        {
            if ( ! isdigit(*(addr + i)) )
            {
                return FALSE;
            }
            *(buf + j) = *(addr + i);
            ++i;
            ++j;
        }
        *(buf + j) = '\0';
        value = atoi(buf);

        if ( (value > 255) || (value < 0) )
        {
            return FALSE;   
        }
       
        if ( *(addr + i) == '.' )
        {
            ++i;
            j = 0;
            memset(buf, 0, sizeof(buf));
            continue;
        }
        else
        {
            break;
        }
    }

    if ( num == 4 )
        return TRUE;
    else
        return FALSE;
}

阅读(364) | 评论(0) | 转发(0) |
0

上一篇:SourceInsight使用方法

下一篇:rindex

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