C语言判断给定的字符串是否为合法的ip地址

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

输入字符串的时候,把分隔符“.”读取出来,然后判断分隔符旁边的数字是否在0~~255之间,然后判断是否合法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <stdio.h>
#include <string.h>
// www.sharejs.com
int main(void
{
    char str[31],temp[31];
    int a,b,c,d;
    while(gets(str)!=NULL)
    {
        if(sscanf(str, "%d.%d.%d.%d ",&a,&b,&c,&d)==4 &&   a>=0   &&   a<=255 &&   b>=0   &&   b<=255 &&   c>=0   &&   c<=255 &&   d>=0   &&   d<=255)
        {
            sprintf(temp, "%d.%d.%d.%d",a,b,c,d);    //把格式化的数据写入字符串temp
            if(strcmp(temp,str)==0) 
            {
                printf("YES\n"); 
            
            else
            {
                printf("NO\n"); 
            }
        }
        else 
        {
            printf("NO\n");
        }
    }
    return 0; 
}