// Program to check if a IP address is vaild.
// By DreamVB 21:04 04/11/2016

#include <iostream>
#include <string>

using namespace std;
using std::cout;
using std::endl;

bool IsIPGood(string src){
	int i = 0;
	int j = 0;
	int num = 0;
	string Parts[4];
	string buffer = "";
	int cnt = 0;
	bool IsGood = true;

	while (i < src.length()){
		//Check for .
		if (src[i] == '.'){
			if (cnt > 2){
				IsGood = false;
				break;
			}
			//Check buffer length
			if (buffer.length() == 0){
				IsGood = false;
				break;
			}
			else{
				Parts[cnt] = buffer;
				buffer.clear();
				cnt++;
			}
		}
		if (src[i] != '.'){
			//Build string
			buffer += src[i];
		}
		i++;
	}

	if (buffer.length() == 0){
		IsGood = false;
	}
	else{
		Parts[cnt] = buffer;
		buffer.clear();
	}

	if (cnt != 3){
		IsGood = false;
	}
	//Check for vaild digits

	i = 0;
	j = 0;

	while (i <= cnt){
		//Check for only digits.
		for (j = 0; j < Parts[i].length(); j++){
			if (!isdigit(Parts[i][j])){
				IsGood = false;
				break;
			}
		}
		//Get number from string
		num = 0;
		for (j = 0; j < Parts[i].length(); j++){
			num = num * 10 + Parts[i][j] - '0';
		}

		//Check for vaild range
		if (num < 0 | num>255){
			IsGood = false;
			break;
		}
		i++;
	}

	return IsGood;
}


int main(int argc, char *argv[]){

	char c = 'Y';
	string sIp = "";

	while (c == 'Y'){
		cout << "Enter a IP address /> ";

		cin.ignore();
		getline(cin,sIp);

		if (!IsIPGood(sIp)){
			cout << "The IP address entered is invalid." << endl;
		}
		else{
			cout << "The IP address is valid." << endl << endl;
		}
		cout << "Do you want to check another y/n : ";
		cin >> c;

		if (c > 97){
			c = (char)(c - 32);
		}

		//Check choice
		if (c == 'N'){
			cout << "Thanks for using the program." << endl;
		}
		else{
			if (c != 'Y'){
				cout << "Invalid choice '" << c << "' entered." << endl;
				break;
			}
		}

	}
	system("pause");
	return 0;
}