在接触的项目中,遇到了需要判断IP地址是否合法的需求,用纯C++和Qt的方式,分别写了一种,如下所示。
Qt的方式:
bool ipAddrIsOK(const QString & ip)
{
if (ip.isEmpty())
{
return false;
}
QStringList list = ip.split('.');
if (list.size() != 4)
{
return false;
}
for (const auto& num : list)
{
bool ok = false;
int temp = num.toInt(&ok);
if (!ok || temp < 0 || temp > 255)
{
return false;
}
}
return true;
}
C++的方式:
bool ipAddrOK(const std::string& ipAddr) const
{
if (ipAddr.empty())
{
return false;
}
std::istringstream iss(ipAddr);
std::vector<std::string> subStrs;
std::string strTemp;
while (getline(iss, strTemp, '.'))
{
subStrs.push_back(strTemp);
}
if (4 != subStrs.size())
{
return false;
}
bool ok = true;
for (const auto& str : subStrs)
{
if (!str2IntOK(str))
{
ok = false;
break;
}
}
return ok;
}
bool str2IntOK(const std::string & rawStr) const
{
if (rawStr.empty())
{
return false;
}
auto iter = rawStr.begin();
for (; iter!=rawStr.end(); ++iter)
{
if (*iter < '0' || *iter > '9')
{
return false;
}
}
int data = stoi(rawStr);
if (0 <= data && data <= 255)
{
return true;
}
return false;
}
总的来说比较简单,此篇博客仅做记录用。