代码如下:
#include <iostream>
#include <algorithm>
using namespace std;
class Solution
{
public:
string validIPAddress(string IP)
{
//以.和:来区分ipv4和ipv6
for (int i = 0; i < IP.length(); i++)
{
if (IP[i] == '.')
return isIPv4(IP) ? "IPv4" : "Neither";
else if (IP[i] == ':')
return isIPv6(IP) ? "IPv6" : "Neither";
}
return "Neither";
}
private:
bool isIPv4(string IP)
{
int dotcnt = 0;
//数一共有几个.
for (int i = 0; i < IP.length(); i++)
{
if (IP[i] == '.')
dotcnt++;
}
//ipv4地址一定有3个点
if (dotcnt != 3)
return false;
string temp = "";
for (int i = 0; i < IP.length(); i++)
{
if (IP[i] != '.')
temp += IP[i];
//被.分割的每部分一定是数字0-255的数字
if (IP[i] == '.' || i == IP.length() - 1)
{
if (temp.length() == 0 || temp.length() > 3)
return false;
for (int j = 0; j < temp.length(); j++)
{
if (!isdigit(temp[j]))
return false;
}
int tempInt = stoi(temp);
if (tempInt > 255 || tempInt < 0)
return false;
string convertString = to_string(tempInt);
if (convertString != temp)
return false;
temp = "";
}
}
if (IP[IP.length()-1] == '.')
return false;
return true;
}
bool isIPv6(string IP) {
int dotcnt = 0;
for (int i = 0; i < IP.length(); i++)
{
if(IP[i] == ':')
dotcnt++;
}
if (dotcnt != 7) return false;
string temp = "";
for (int i = 0; i < IP.length(); i++)
{
if (IP[i] != ':')
temp += IP[i];
if (IP[i] == ':' || i == IP.length() - 1)
{
if (temp.length() == 0 || temp.length() > 4)
return false;
for (int j = 0; j < temp.length(); j++)
{
if (!(isdigit(temp[j]) ||(temp[j] >= 'a' && temp[j] <= 'f') || (temp[j] >= 'A' && temp[j] <= 'F')))
return false;
}
temp = "";
}
}
if (IP[IP.length()-1] == ':')
return false;
return true;
}
};
int main()
{
Solution sol;
string s;
while(1){
cout << "Please input a string: " << endl;
cin >> s;
if(s == "exit"){
break;
}
cout << sol.validIPAddress(s) << endl;
}
cout << "bye" << endl;
return 0;
}
运行结果:
|