判断IP合法性和纯数字合法性

1. 判断IP地址是否合法

描述:下面封装了两个函数,判断字符串中的IP是否合法。

#include <string>
using namespace std;


bool CSettingDlg::isok(string str,int num)  
{  
	int len=str.length();  
	int d=0;  

	if(str=="0") return true;  
	if(len>1&&str[0]=='0') return false; //有前导0,不合法  

	for(int i=0;i<len;i++)  
	{  
		if(!isdigit(str[i])&&str[i]!=' ')  return false;  

		if(str[i]==' ')  
		{  
			if(num==2||num==3) return false;  
			else  
			{  
				if(num==1&&i!=0&&str[i]==' ') return false;  
				if(num==4&&i!=len-1&&str[i]==' ') return false;  
			}  
		}  
		if(isdigit(str[i])){  
			d=d*10+str[i]-'0';  
		}  
	}  
	if(d<0||d>255) return false;  
	return true;  
}  
bool CSettingDlg::isIPAddressValid(const char* pszIPAddr)  
{  
	// 请在此处实现  
	if(pszIPAddr==NULL) return false;  
	string str=string(pszIPAddr);  
	int len=str.length();  

	int coma_num;   //=numberofComa(str);  //计数点号,如果点号的个数不等于3个则为非法  

	//在str最后加上一个小数点,为了统计方便  
	str.append(".");  

	//下面开始分割字符串,用点号进行分割,得到每个字符串,如果字符串,不合法,则返回false,不合法情况包括,字符串中间有空格,字符串有前导0,字符串中数字不再0-255之间,还有字符串为空,,这些都是不合法  
	//string::iterator iter_pre=str.begin(),iter_post;  

	int iter_pre=0;  
	int iter_post=str.find('.',iter_pre);  
	if(iter_post==str.npos) return false;  
	coma_num=0;  

	while(iter_post!=str.npos)  
	{  
		coma_num++;  
		string substr=str.substr(iter_pre,iter_post-iter_pre);  
		if(substr=="") return false;   
		if(!isok(substr,coma_num)) //如果不合法,跳出,并返回false  
		{  
			return false;  
		}  
		iter_pre=iter_post+1;  

		iter_post=str.find('.',iter_pre);     
	}  
	if(coma_num!=4) return false;  
	return true;  
}  


调用:

if (!isIPAddressValid(m_strIP.GetBuffer()))
	{
		AfxMessageBox("IP不合法!!!");
		return;
	}

2. 纯数字合法性

描述:判断字符串中的内容是否都是数字。


if(!(strPort.SpanIncluding(_T("0123456789")) == strPort))
	{
		AfxMessageBox("端口不合法,不是纯数字!!!");
		return;
	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值