我们除了使用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(".");
if (pos == 0)
return false;
std::string s1 = sip.substr(0, pos);
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());
if (a < 1 || a>255)
return false;
pos = (int)sip.find_first_of(".");
std::string s2 = sip.substr(0, pos);
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)
return false;
pos = (int)sip.find_first_of(".");
std::string s3 = sip.substr(0, pos);
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)
return false;
pos = (int)sip.find_first_of(".");
std::string s4 = sip.substr(0, pos);
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)
return false;
return true;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)