#include <netdb.h>
#include <netinet/in.h>
#include <stdio.h>


unsigned long get_addr(char *s)
{
	unsigned long	addr;
	struct hostent	*hp;
	struct netent	*np;

	addr = inet_addr(s);
	if (addr == (unsigned) -1) {
		if (!(hp = gethostbyname(s))) {
			if (!(np = getnetbyname(s))) {
				fprintf(stderr, "%s: address not known\n", s);
				exit(1);
			}
/* KLUDGE: n_net doesn't seem to be set correctly (libc 4.4) */
			if ((addr = htonl(np->n_net)) == 0xffffffff)
				addr = inet_addr(np->n_name);
		} else {
			addr = **((unsigned long **)(hp->h_addr_list));
		}
	}

	return ntohl(addr);
}


main(int argc, char *argv[])
{
	unsigned long	addr, net, mask;

	if (argc != 2 && argc != 3) {
		printf("usage: netaddr host|net [netmask]\n");
		exit(1);
	}

	addr = get_addr(argv[1]);
	if (argc == 3) {
		mask = ntohl(inet_addr(argv[2]));
	} else {
		if (IN_CLASSC(addr)) {
			mask = IN_CLASSC_NET;
		} else if (IN_CLASSB(addr)) {
			mask = IN_CLASSB_NET;
		} else {
			mask = IN_CLASSA_NET;
		}
	}

	printf("%s\n", inet_ntoa(htonl(addr & mask)));

	exit(0);
}
