判断输入字段是否为IP地址

判断输入字段是否为IP地址,仅供参考:

#include<stdio.h>                                                               
#include<string.h>
#include<stdlib.h>

//检查字符是否是在16进制字母中
static  int  String_Hex(char *p)
{
   int  ret = 0;
    if (p == NULL)
    {
        ret = 0;
    }
    else
    {
		while (*p)
        {

            if (((*p >= 'a') && (*p <= 'f')) || ((*p >= 'A') && (*p <= 'F')))
            {
                ret = 1;
                break;
            }
            else
            {
                ret = 0;
            }
            p++;
        }
    }
    return ret;
}
int  checkIP(const  char * str)
{
    	int  ret = 0;
    	const char * split = ".";
    	char *str1;
    	char * p;
    	int  seg_num = 0;
    	int  ip[10] = { 0 };
    	long  num = 0;
        int i = 0;
    	int correct = 0;
    	if (str == NULL)
   		{
        	printf("str is null\n");
        	ret = 0;
    	}
    	else
    	{
        	str1 = (char*)malloc(strlen(str) + 1);
        	strcpy(str1, str);
        	//分割字符串
        	p = strtok(str1, split);
        	while (p != NULL) 
        	{
            	if (String_Hex(p))
            	{
 					num = strtol(p, NULL, 16);
            	}
            	else
            	{
                num = strtol(p, NULL, 10);
            }
            printf("p:%s        ", p);
            ip[seg_num] = num;
            printf("ip[seg_num]=%d\n", ip[seg_num]);
            seg_num++;
            p = strtok(NULL, split);
        }
 		if (seg_num == 4)
        {
            for (i = 0; i < seg_num; i++)
            {
                if ((ip[i] >= 0) && (ip[i] <= 255))
                    correct++;
            }
            if (correct == 4)
            {
                ret = 1;
            }
            else
            {
                ret = 0;
            }
        }
        else
        {
            ret = 0;
        }

    }

    return ret;
}
int  main()
{
    	char str[20] = {0};
    	int  ret = 0;
    	printf("输入IP地址\n");
    	scanf("%s",str);
    	ret = checkIP(str);
    	if (ret == 0)
    	{
        	printf("IP  无效\n");
        }
        else if (ret == 1)
         {
          printf("IP  有效\n");
         }
    	printf("hello\n");
    	return  0;
}                
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值