判定字符串形式IP是否有效

//判定字符串形式IP是否有效
#include"stdio.h"
#include"string.h"
void main()
{
    char str[17];
    int a = 0;
    int b = 0;
    int c = 0;
    int d = 0;
    while (fgets(str, sizeof(str), stdin) != NULL)
    {
        str[strlen(str)] = '\0';//字符串终止符别忘哈
        //sscanf函数将字符串IP扔到a.b.c.d整数中去
        int num=sscanf(str,"%d.%d.%d.%d",&a,&b,&c,&d);
        if ((num == 4) && (a >= 0 && a <= 255) && ((b >= 0 \
             && b <= 255)) && ((c >= 0 && c <= 255))\
             && ((d >= 0 && d <= 255)))//基于整数abcd做有效判定
            printf("ip:%s\n", str);
        else
            printf("not ip\n");
    }
}

猜你喜欢

转载自blog.csdn.net/acttell/article/details/74136729