Friday, April 22, 2022

c++ Program to validate an IPV4 address

c++ Program to validate an IPV4 address

c++ Program to validate an IPV4 address

#include <bits/stdc++.h>

using namespace std;

 class Solution {

public:

int isValid(string s) 

{

if(s.size() < 7)  //minimum lenght of ip address 0.0.0.0

return 0;


//check for minimum and maximum three dots

size_t _count = std::count(s.begin(), s.end(), '.');

if( _count != 3)

return 0;


string tmpStr(s);

string currVal;

int currValInt;

int pos;

while(_count > 0)

{

pos = tmpStr.find('.');

currVal = tmpStr.substr(0, pos);

if(!isdigit(currVal[0]))        //to check a.b.c.d

return 0;

currValInt = stoi(currVal);


if(currValInt == 0 && currVal.size()>1)     //000.000.000.000

break;


if(currVal.size() > 3)                      //3343.46546.323.11

break;


if(currValInt > 255 || currValInt < 0 )         //300.333.266.32

break;


if((currValInt < pow(10,currVal.length()-1)) && (currValInt != 0))      //01.022.22.44

return 0;


tmpStr = tmpStr.substr(pos + 1);

_count--;

}

if(_count > 0)

return 0;

//Now validate the last element of the IP address i.e. out of x1.x2.x3.x4 validate x4

currValInt = stoi(tmpStr);

if(currValInt == 0 && tmpStr.size() > 1)

return 0;

if(tmpStr.size() == 0 || tmpStr.size() > 3)

return 0;

if(stoi(tmpStr) > 255 || stoi(tmpStr) < 0 )

return 0;

if((currValInt < pow(10,tmpStr.length()-1)) && (currValInt != 0))

return 0;


return 1;

}

};


int main() {

string s;

cin >> s;

Solution ob;

cout << ob.isValid(s) << endl;

    return 0;

}


No comments:

Post a Comment