/*
 * 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 "ipv4addr.h"

#include <cstdio>

#include <qstring.h>


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


IPv4Addr::IPv4Addr(const in_addr &  iaddr) {
	addr = iaddr;
	valid = true;
}


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

/** Returns FALSE if both IP addresses are valid and
  * don't equal, otherwise TRUE.
  */
bool	IPv4Addr::operator ==(const IPv4Addr &  obj) {
	return  ((valid && obj.valid) ? (addr.s_addr == obj.addr.s_addr) : true);
}

/** Returns TRUE if both IP addresses are valid and
  * don't equal, otherwise FALSE.
  */
bool	IPv4Addr::operator !=(const IPv4Addr &  obj) {
	return  !operator==(obj);
}

/** Marks this address as invalid.
  *
  */
void  IPv4Addr::setInvalid() {
	valid = false;
}

/** Extract ip address from an integer array and store it if valid.
  *
  * @return TRUE if the given ip is valid and
  *			was stored, FALSE if it is invalid
  *			and the address was set to 0.0.0.0
  */
bool	IPv4Addr::setAddr(const QString &  str) {
	if(str.isEmpty()) {
		valid = false;
		return  false;
	}

	int  addrlen = inet_net_pton(AF_INET, str, &addr, sizeof(addr));
	uint8_t *s_addr = (uint8_t*) &addr.s_addr;
	if(addrlen <= 0 || s_addr[3] == 0x00)
		valid = false;
	else
		valid = true;

	return  valid;
}

bool	IPv4Addr::isValid() const {
	return valid;
}

/** @return The stored IP address converted into QString. */
QString  IPv4Addr::toString() const {
	static char	tmpbuf[16];

	return	valid ? QString(inet_ntop(AF_INET,  &addr,  tmpbuf,  sizeof tmpbuf)) : "";
}

/** @return The stored IP address converted to in_addr_t. */
in_addr_t IPv4Addr::toInetAddr() const {
	return	addr.s_addr;
}
