/*
 *  Copyright (C) 2007-2008 CMM Sigma Andrzej Chmielowiec <cmmsigma@cmmsigma.eu>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License version 3
 *  as published by the Free Software Foundation.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 */

#include "ipaddr.h"

#include <QStringList>
#include <QMessageBox>

bool
checkIpAddrSyntax(QString ipaddr)
{
	ipaddr.remove(QRegExp("\\s+"));
	QStringList parts = ipaddr.split(QChar('.'));
	bool ok;
	
	if (parts.size() != 4)
		return false;
	
	for (int i = 0; i < parts.size(); i++)
	{
		int part = parts[i].toInt(&ok);
		
		if (!ok)
			return false;
		
		if (part < 0 || 255 < part)
			return false;
	}
	
	return true;
}

bool
checkNetMaskSyntax(QString netmask)
{
	netmask.remove(QRegExp("\\s+"));
	QStringList parts = netmask.split(QChar('.'));
	bool ok;
	
	if (parts.size() != 4)
		return false;
	
	bool restShouldBeZeros = false;
	
	for (int i = 0; i < parts.size(); i++)
	{
		int part = parts[i].toInt(&ok);
		
		if (!ok)
			return false;
		
		if (restShouldBeZeros)
		{
			if (part != 0) return false;
			else continue;
		}
		
		if (part == 255)
			continue;
		
		if (part == 254 || part == 252 || part == 248 || part == 240
			|| part == 224 || part == 192 || part == 128 || part == 0)
		{
			restShouldBeZeros = true;
			continue;
		}
		
		return false;
	}
	
	return true;
}
