判断一个字符串是否是域名或者IP的小程序

int _IsValid(char *str)   //检测给函数传递的参数格式是否正确  1为IP 2为域名
{
 int Num = 0;   //字符串中数字出现的次数
 int StrCount = 0;  //字符串总字数
 int point = 0;   //字符串中 . 出现的次数
 int Word = 0;   //字符串中字母出现的次数
 int FormatError = 0; //如果字符串中有2个连续的 - 则出错返回
 char *ForCheck = NULL; //字符指针
 char CopyStr[255] = ""; //把传进来的字符串进行处理,大写变小写

 if (str[strlen(str)-1] == '\n')  //如果参数中有 \n 则删除
  str[strlen(str)-1] = '\0';

 if(!strcpy_s(CopyStr,255,str))
 {
  return -1;   //如果字符串大小超过255 那么不是一个域名,更不是一个IP
 }
 
 for(int i = 0;i<255;i++)
 {
  if( CopyStr[i] >= 97 && CopyStr[i] <= 122 )
  {
   CopyStr[i] -= 32;
  }
 }

 while((*ForCheck) != NULL)
 {
  if ( ((*ForCheck) >= '0'&& (*ForCheck) <= '9'))
  {
   FormatError = 0;
   Num++;
  }
  else if ((*ForCheck) == '.')
  {
   FormatError = 0;
   point++;
  }
  else if(  ( (*ForCheck) >= 'a' && (*ForCheck) <= 'z') )
  {
   FormatError = 0;
   Word++;
  }
  else if ((*ForCheck) == '-' )
  {
   FormatError++;
   
   if(FormatError > 1)   //连续2次出现 - 则出错返回
   {
    return -1;
   }
  }
  else       //出现其他符号,直接返回错误
   return -1;
  

  StrCount++;
  ForCheck++;
 }

 if (((Num+point) == StrCount )&& ( point == 3 ) )  //如果为IP地址 那么 . 和数字的和应该等于字符串大小
 {
  return 1;
 }
 else if (  (Num+point+Word) == StrCount )   //如果字符串由三种元素组成,那么判断是否是域名
 {
  ForCheck = str;

  if (point == 1 || point == 2)         //如果有以下后缀 那么肯能是个域名
  {    
   if( strstr(ForCheck,".com")  || strstr(ForCheck,".net") ||   
    strstr(ForCheck,".org")  || strstr(ForCheck,".edu") ||
    strstr(ForCheck,".mil")  || strstr(ForCheck,".gov") ||
    strstr(ForCheck,".biz")  || strstr(ForCheck,".info")||
    strstr(ForCheck,".name") || strstr(ForCheck,".pro") ||
    strstr(ForCheck,".aero") || strstr(ForCheck,".coop")||
    strstr(ForCheck,".museum") )
   {
    return 2; //是否为域名,利用gethostbyname函数的返回值来判断
   }
   else
    return -1;
  }
  else
   return -1;

 }

 return -3; //程序意外退出
}

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值