[MFC]使用编辑框来设置IP地址

我们除了使用IP控件来设置控件之外还可以使用编辑框来设置IP,这样的话,就需要来进行判断我们输入的IP是否合法

判断IP地址合法的标准:
①字符串中必须包含3个符号“.”;
②被符号“.”分隔的4个字符串的长度必须小于或等于3
③被符号“.”分隔的4个字符串必须可以转换成整数;
④被符号“.”分隔的4个字符串转换成的整数不得大于255

bool IsValidIP(char *ip)
{
     std::string sip = ip;
	int pos = (int)sip.find_first_of(".");//查找第1个符号“.”的位置
	if (pos == 0)//如果没有找到,则返回false
		return false;
	std::string s1 = sip.substr(0, pos);//s1是IP地址中的第1个数字
	sip = sip.substr(pos + 1, sip.length() - pos);
	if (s1.length() > 3)
		return false;
	for (int i = 0; i < (int)s1.length(); i++)//判断是否每个字符都是数字
	{
		int c = s1.c_str()[i];
		if (!isdigit(c))
			return false;
	}
	int a = atoi(s1.c_str());//判断是否在1~255之间
	if (a < 1 || a>255)
		return false;
	pos = (int)sip.find_first_of(".");
	std::string s2 = sip.substr(0, pos); //s2是IP地址中的第2个数字
	sip = sip.substr(pos + 1, sip.length() - pos);
	if (s2.length() > 3)
		return false;
	for (int i = 0; i < (int)s2.length(); i++)//判断是否每个字符都是数字
	{
		int c = s2.c_str()[i];
		if (!isdigit(c))
			return false;
	}
	a = atoi(s2.c_str());
	if (a > 255)//判断是否在0~255之间
		return false;
	pos = (int)sip.find_first_of(".");
	std::string s3 = sip.substr(0, pos); //s3是IP地址中的第3个数字
	sip = sip.substr(pos + 1, sip.length() - pos);
	if (s3.length() > 3)
		return false;
	for (int i = 0; i < (int)s3.length(); i++)//判断是否每个字符都是数字
	{
		int c = s3.c_str()[i];
		if (!isdigit(c))
			return false;
	}
	a = atoi(s3.c_str());
	if (a > 255)//判断是否在0~255之间
		return false;
	pos = (int)sip.find_first_of(".");
	std::string s4 = sip.substr(0, pos); //s4是IP地址中的第4个数字
	sip = sip.substr(pos + 1, sip.length() - pos);
	if (s4.length() > 3)
		return false;
	for (int i = 0; i < (int)s4.length(); i++)//判断是否每个字符都是数字
	{
		int c = s4.c_str()[i];
		if (!isdigit(c))
			return false;
	}
	a = atoi(s4.c_str());
	if (a > 254)//判断是否在0~254之间
		return false;
	//通过上面所有检测后,确定该字符串为合法IP地址
	return true;
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值