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; //程序意外退出
}