// Class version of checking for vaild IP address
// By DreamVB 23:38 04/11/2016

#include <iostream>
#include <string>

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

class TIPChecker{
	private:
		bool IsGood = true;
	public:
		TIPChecker(string Address){
			int i = 0;
			int j = 0;
			int num = 0;
			string Parts[4];
			string buffer = "";
			int cnt = 0;

			while (i < Address.length()){
				//Check for .
				if (Address[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 (Address[i] != '.'){
					//Build string
					buffer += Address[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++;
			}
		}

		const bool IsVaild() const{
			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);
		TIPChecker ipchk(sIp);

		try{
			if (!ipchk.IsVaild()){
				throw std::exception("The IP address entered is invalid.");
			}
			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'){
					throw std::invalid_argument("Invalid choice entered.");
				}
			}
		}
		catch (exception& e){
			cout << typeid(e).name() << endl <<
				e.what() << endl;
			break;
		}
	}

	system("pause");
	return 0;
}