IP地址是否合法的判斷方法,IP字符串是否合規

對於網上的一些方法,這裏代碼做了一下完善。直接上代碼:


bool isValidIP(char* str){

	bool preIsNum=false;
	int numOfPoint=0;
	int numOfNum=0;
	char *p=str;

	if (NULL==str)
	{
		return false;
	}


	while ('\0'!=*p)
	{
		if('.'!=*p && (*p<'0'||*p>'9'))
		{
			return false;
		}

		if('.'==*p)
		{
			 if (!preIsNum)
			 {
				 return false;
			 }
			 else
			 {
				 preIsNum=false;
				 numOfPoint++;
			 }
			 p++;
		}
		else
		{
			int tmp=0;
			bool prevHasZero=false;
			while ('\0' != *p && *p>='0' && *p<='9')
			{
				if (prevHasZero==true)
				{
					return false;
				}
				if (*p=='0'&&tmp==0)
				{
					 prevHasZero=true;
				}
				tmp=tmp*10+(*p-'0');
				p++;
			}
			if (tmp<0||tmp>255)
			{
				return false;
			}
			numOfNum++;
			preIsNum=true;
		}
	}

	if (numOfPoint==3 && numOfNum==4)
	{
		return true;
	}
	else
	{
		return false;
	}
}

找了一些樣例進行測試:

"192.168.1.1" is vaild.
"255.255.255.255" is vaild.
"0.0.0.0" is vaild. 
"192.1222.21.1" is not vaild.
"a.22.222.1.1" is not vaild.
"10.01.22.22" is not vaild.
"192..2.1.2" is not vaild.
"213.22.200.100.221.12" is not vaild.
"213.22.200.100." is not vaild.
".192.201.23.2" is not vaild.
"%.32#.33#.a" is not vaild.
"256.33.22.33" is not vaild.
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章