class Solution {
public:
/**
* 验证IP地址
* @param IP string字符串 一个IP地址字符串
* @return string字符串
*/
string solve(string IP) {
istringstream is(IP);
string tmp = "";
int cnt = 0;
if (IP.find(':')==IP.npos) {
while (getline(is, tmp, '.')) {
++cnt;
if (cnt > 4 || tmp.empty() || tmp.size() > 1 && tmp[0] == '0' || tmp.size() > 3)
return "Neither";
for (char t : tmp) {
if (t > '9' || t < '0') return "Neither";
}
int val = stoi(tmp);
if (val < 0 || val>255) return "Neither";
}
return (cnt == 4 && IP.back() != '.') ? "IPv4" : "Neither";
}
else {
while (getline(is, tmp, ':')) {
++cnt;
if (cnt > 8 || tmp.empty() || tmp.size() > 4) return "Neither";
for (char t : tmp) {
if (!(t >= '0' && t <= '9') && !(t >= 'a' && t <= 'f') && !(t >= 'A' && t <= 'F'))
return "Neither";
}
}
return (cnt == 8 && IP.back() != ':') ? "IPv6" : "Neither";
}
}
};
class Solution {
public:
string validIPAddress(string IP) {
regex ipv4("(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])");
regex ipv6("([0-9a-fA-F]{1,4}\\:){7}[0-9a-fA-F]{1,4}");
if (regex_match(IP, ipv4)) return "IPv4";
else if (regex_match(IP, ipv6)) return "IPv6";
else return "Neither";
}
};
class Solution {
public:
string validIPAddress(string IP) {
if (isValidIPv4(IP)) return "IPv4";
if (isValidIPv6(IP)) return "IPv6";
return "Neither";
}
// 优雅的split
void split(const string s, vector<string>& vs, const char delim= ' '){
istringstream iss(s);
string temp;
while (getline(iss,temp,delim)){
vs.emplace_back(move(temp));
}
if (!s.empty() && s.back() == delim) vs.push_back({});//加这句的原因是getline不会识别最后一个delim,避免误判"172.16.254.1.","2001:0db8:85a3:0:0:8A2E:0370:7334:"之类的情况
}
// 判定是否IPv4
bool isValidIPv4(string IP){
vector<string> vs;
split(IP,vs,'.');
if (vs.size()!=4) return false;
for (auto &v:vs) {
if (v.empty() || (v.size()>1 && v[0] == '0') || v.size()>3) return false;
for (auto c:v) {
if (!isdigit(c)) return false;
}
int n = stoi(v);
if (n<0||n>255) return false;
}
return true;
}
// 判定是否IPv6
bool isValidIPv6(string IP){
vector<string> vs;
split(IP,vs,':');
if (vs.size()!=8) return false;
for (auto &v:vs) {
if (v.empty() || v.size()>4 ) return false;
for (auto c:v){
if (!(isdigit(c) || (c>='a'&&c<='f') || (c>='A'&&c<='F'))) return false;
}
}
return true;
}
};