判断一个字符串是否是域名或者IP的小程序
2012-03-22 10:46
330 查看
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; //程序意外退出
}
相关文章推荐
- Java 写一个方法判断一个字符串是否对称 "asdfgasdfg"、编写一个程序,将下面的一段文本中的各个单词的字母顺序翻转,
- 判断一个值或者字符串是否在数组中
- 判断一个字符串的ip是否是IP合法的ip地址
- 判断一个字符串是否为合法IP
- 判断一个字符串的ip是否是IP合法的ip地址
- 判断一个字符串是否为空(null)或者是空字符串(“”)的方法和总结
- C#判断一个字符串是否是数字或者含有某个数字
- java判断输入的字符串是否是一个IP
- 用一个Python程序来判断一个字符串是否是另一个字符串的sublist
- 判断一个字符串是否是有效IP(包括IPv4和IPv6)
- oracle判断一个字符串中是否包含另外一个字符串(想要不论顺序或者不相邻的字符)
- C#判断一个字符串是否是数字或者含有某个数字的方法
- 一个简单的判断字符串所含字母是否有大写,并将所有字母改为大写的小程序
- 用C语言编写程序,判断输入的一个字符串是否是回数
- 编写一个函数isMerge,判断一个字符串str是否可以由其他两个字符串part1和part2“组合”而成
- 判断字符串是否是回文字符串或者是否含有回文字符子串 (我是从两颗番茄的博客看的题目,然后自己编的) 不断学习!!
- smarty中判断一个变量是否存在于一个数组中或是否存在于一个字符串中?
- 编写函数,判断一个字符串是否是回文
- 判断一个字符串中是否包含另一个字符串
- Java判断字符串是否是整数或者浮点数的方法