/*
 * This file is part of DesktopBSD, see the README file.
 *
 * Author: Peter Hofer <ph@desktopbsd.net>
 *			(C) 2004, 2005
 *
 * Copyright: BSD, see the COPYING file included in this distribution
 *
 */

#include "ipv4netmask.h"

#include <qstring.h>

IPv4Netmask::IPv4Netmask() {
	valid = false;
}


IPv4Netmask::IPv4Netmask(const QString &  str) {
	setAddr(str);
}


IPv4Netmask::IPv4Netmask(const in_addr &  saddr) {
	setAddr(saddr);
}


bool IPv4Netmask::setAddr(in_addr  iaddr) {
	addr = iaddr;

	uint8_t  *s_addr = (uint8_t*) &addr.s_addr;
	const uint32_t validMasks[] = {
												 0xffffffff, 0xfffffffe, 0xfffffffc, 0xfffffff8, 0xfffffff0,
												 0xffffffe0, 0xffffffc0, 0xffffff80, 0xffffff00, 0xfffffe00,
												 0xfffffc00, 0xfffff800, 0xfffff000, 0xffffe000, 0xffffc000,
												 0xffff8000, 0xffff0000, 0xfffe0000, 0xfffc0000, 0xfff80000,
												 0xfff00000, 0xffe00000, 0xffc00000, 0xff800000, 0xff000000,
												 0xfe000000, 0xfc000000, 0xf8000000, 0xf0000000, 0xe0000000,
												 0xc0000000, 0x80000000, 0x00000000
											};

	uint32_t hex = s_addr[0] * 0x1000000 + s_addr[1] * 0x10000 +
						s_addr[2] * 0x100 + s_addr[3];
	for(uint i = 0; i < sizeof(validMasks) / sizeof(validMasks[0]); ++i)
		if(hex == validMasks[i]) {
			valid = true;
			break;
		}

	return  valid;
}


/** This reimplements IPv4Addr::setAddr(const QString&)
  * and makes sure only valid *Netmasks* are used
  */
bool IPv4Netmask::setAddr(const QString &  str) {
	if(str.isEmpty())
		return  (valid = false);

	int  addrlen = inet_net_pton(AF_INET, str.latin1(), &addr, sizeof(addr));
	if(addrlen <= 0)
		return  (valid = false);

	return  setAddr(addr);
	uint8_t  *s_addr = (uint8_t*) &addr.s_addr;
	const uint32_t validMasks[] = {
												 0xffffffff, 0xfffffffe, 0xfffffffc, 0xfffffff8, 0xfffffff0,
												 0xffffffe0, 0xffffffc0, 0xffffff80, 0xffffff00, 0xfffffe00,
												 0xfffffc00, 0xfffff800, 0xfffff000, 0xffffe000, 0xffffc000,
												 0xffff8000, 0xffff0000, 0xfffe0000, 0xfffc0000, 0xfff80000,
												 0xfff00000, 0xffe00000, 0xffc00000, 0xff800000, 0xff000000,
												 0xfe000000, 0xfc000000, 0xf8000000, 0xf0000000, 0xe0000000,
												 0xc0000000, 0x80000000, 0x00000000
											};

	uint32_t hex = s_addr[0] * 0x1000000 + s_addr[1] * 0x10000 +
						s_addr[2] * 0x100 + s_addr[3];
	for(uint i = 0; i < sizeof(validMasks) / sizeof(validMasks[0]); ++i)
		if(hex == validMasks[i]) {
			valid = true;
			break;
		}

	return  valid;
}
