我们除了使用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;
}