判断输入的ip字符串格式的合法性
2014-06-15 17:24
369 查看
ipv4的ip格式共32位,每8位用一个10进制数表示,中间为.如192.168.8.104
字符串输入正确,如192.168.8.104
输出YES
不正确,如192.c.8.104或192. 258.8.104呀192 .168.8.104
输出 NO
字符串输入正确,如192.168.8.104
输出YES
不正确,如192.c.8.104或192. 258.8.104呀192 .168.8.104
输出 NO
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> int isIn255(int ipSeg[],int cnt) { int value; if(cnt==1) { value=ipSeg[0]; if(value>=0&&value<256) return 1; return 0; } else if(cnt==2) { value=ipSeg[0]*10+ipSeg[1]; if(value>0&&value<256) return 1; return 0; } else if(cnt==3) { value=ipSeg[0]*100+ipSeg[1]*10+ipSeg[2]; if(value>0&&value<256) return 1; return 0; } else return 0; } int islegal(char *str) { char *p=str; int ipSeg[3]; int len; int cnt,i; char curChar; for(i=0;i<4;i++) { cnt=0; while(*p!='.'&&*p!='\0') { if(cnt>2) return 0; //非法 if(isdigit(curChar=*p)) { ipSeg[cnt]=curChar-'0'; cnt++; } else return 0; p++; } if(!isIn255(ipSeg,cnt)) return 0; //非法 p++; } return 1; } int main() { char ipStr[16]; int flag; scanf("%[^\n]",ipStr); flag=islegal(ipStr); printf("%s\n",flag==1?"YES":"NO"); return 0; }
相关文章推荐
- Java面试宝典系列之字符串转整型、判断IP合法性、求最大公约数
- java 判断字符串IP合法性以及获取IP的数值形式
- Java面试宝典系列之字符串转整型、判断IP合法性、求最大公约数
- 判断输入的IP格式是否正确
- C# 判断IP格式是否正确,字符串类型IPV4地址
- 判断字符串是否是正确的IP格式的C语言函数
- 【Android 开发】使用正则表达式判断输入字符串是否为电话格式
- 判断输入IP格式是否正确
- js判断输入的字符串是否是日期格式
- java判断输入的字符串是否是一个IP
- 判断输入的字符串是否是日期格式的简单方法
- 【JS】:JS实现判断输入字符串是否合乎邮箱格式
- asp.net“输入字符串的格式不正确”之解决
- java 判断输入的字符串是否为正整数
- WinForm 中要求在textBox中输入的内容必须是日期格式yyyy-mm-dd,判断用户输入是否有效!
- JS判断两种格式的输入日期的正确性
- [java]判断输入字符串类型( 附测试数据)
- 如何判断输入的字符串是电子邮件地址
- 判断字符串是否符合数值格式的正则表达式(C#)
- javascript 判断 输入字符串 是否为 数字