Validate IP Address
class Solution {
public:
string validIPAddress(string st) {
//checking ipv4
string s="";
int i=0,l=0,n=st.size();
bool a=true,b=true;
if(st[0]=='0')
a=false;
while(i<n)
{
if(st[i]>='0'&&st[i]<='9')
{
s+=st[i];
}
else if(st[i]=='.')
{
++l;
if((i==n-1)||(st[i+1]=='.')||(s.size()>1&&s.front()=='0'))
{
a=false;
break;
}
stringstream geek(s);
int x=0;
geek>>x;
if(x>=0&&x<=255)
{
s="";
}
else
{
a=false;
break;
}
}else{
a=false;
break;
}
if(i==n-1)
{
stringstream geek(s);
if(s.size()>1&&s.front()=='0')
a=false;
int x=0;
geek>>x;
if(x>=0&&x<=256)
{
s="";
}else{
a=false;
break;
}
}
++i;
}
if(l!=3)
a=false;
i=0,l=0;
int cnt=0;
while(i<n)
{
if((st[i]>='0'&&st[i]<='9')||(st[i]>='a'&&st[i]<='f')||(st[i]>='A'&&st[i]<='F'))
{
++cnt;
}else if(i!=n-1&&st[i]==':'&&st[i+1]!=':')
{
cnt=0;
++l;
}else{
b=false;
break;
}
if(cnt>4)
{
b=false;
break;
}
++i;
}
if(l!=7)
b=false;
if(a)
return "IPv4";
else if(b) return "IPv6";
else
return "Neither";
}
};
----------------------------------------------------------------------------------------------------------------------------
class Solution {
public:
vector<string> split(string IP, char c)
{
vector<string> ip;
string temp;
stringstream ss(IP);
while(getline(ss, temp, c))
{
ip.push_back(temp);
}
return ip;
}
bool valid4(string IP)
{
if(count(IP.begin(), IP.end(), '.') != 3)
return false;
vector<string> ip = split(IP, '.');
if(ip.size() != 4)
return false;
for(auto p : ip)
{
if(p.empty() || p.size() > 3 || (p.size() > 1 && p[0] == '0'))
return false;
for(auto c : p)
if(!isdigit(c))
return false;
if(stoi(p) > 255)
return false;
}
return true;
}
bool valid6(string IP)
{
if(count(IP.begin(), IP.end(), ':') != 7)
return false;
vector<string> ip = split(IP, ':');
if(ip.size() != 8)
return false;
for(auto p : ip)
{
if(p.empty() || p.size() > 4)
return false;
for(auto c : p)
{
if(!isdigit(c) && (!isalpha(c) || toupper(c) > 'F'))
return false;
}
}
return true;
}
string validIPAddress(string IP) {
return valid4(IP) ? "IPv4" : valid6(IP) ? "IPv6" : "Neither";
}
};