netof.c 1.17 KB
Newer Older
1
/* 
Jean-Francois Boudreault's avatar
Jean-Francois Boudreault committed
2
 * netof - return the net address part of an ip address in a sockaddr_storage structure
3 4
 *         (zero out host part)
 */
5
#include <config.h>
6
#include <stdio.h>
7
#include <syslog.h>
8 9

#include "ntp_fp.h"
10
#include "ntp_net.h"
11
#include "ntp_stdlib.h"
Jean-Francois Boudreault's avatar
Jean-Francois Boudreault committed
12
#include "ntp.h"
13

14
sockaddr_u *
15
netof(
16
	sockaddr_u *hostaddr
17 18
	)
{
19 20
	static sockaddr_u	netofbuf[8];
	static int		next_netofbuf;
21
	uint32_t			netnum;
22 23 24 25
	sockaddr_u *		netaddr;

	netaddr = &netofbuf[next_netofbuf];
	next_netofbuf = (next_netofbuf + 1) % COUNTOF(netofbuf);
26

27
	memcpy(netaddr, hostaddr, sizeof(*netaddr));
Jean-Francois Boudreault's avatar
Jean-Francois Boudreault committed
28

29 30
	if (IS_IPV4(netaddr)) {
		netnum = SRCADR(netaddr);
31 32 33 34 35 36

		/*
		 * We live in a modern CIDR world where the basement nets, which
		 * used to be class A, are now probably associated with each
		 * host address. So, for class-A nets, all bits are significant.
		 */
37 38
		if (IN_CLASSC(netnum))
			netnum &= IN_CLASSC_NET;
39
		else if (IN_CLASSB(netnum))
40 41 42 43 44 45
			netnum &= IN_CLASSB_NET;

		SET_ADDR4(netaddr, netnum);

	} else if (IS_IPV6(netaddr))
		/* assume the typical /64 subnet size */
46
		zero_mem(&NSRCADR6(netaddr)[8], 8);
47 48 49 50 51 52 53 54
#ifdef DEBUG
	else {
		msyslog(LOG_ERR, "netof unknown AF %d", AF(netaddr));
		exit(1);
	}
#endif

	return netaddr;
55
}