xref: /freebsd/contrib/ntp/libntp/netof.c (revision b6a05070fa77edc7ce6e60b61623fd806e807be6)
1 /*
2  * netof - return the net address part of an ip address in a sockaddr_storage structure
3  *         (zero out host part)
4  */
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"
12 #include "ntp.h"
13 
14 sockaddr_u *
15 netof(
16 	sockaddr_u *hostaddr
17 	)
18 {
19 	static sockaddr_u	netofbuf[8];
20 	static int		next_netofbuf;
21 	u_int32			netnum;
22 	sockaddr_u *		netaddr;
23 
24 	netaddr = &netofbuf[next_netofbuf];
25 	next_netofbuf = (next_netofbuf + 1) % COUNTOF(netofbuf);
26 
27 	memcpy(netaddr, hostaddr, sizeof(*netaddr));
28 
29 	if (IS_IPV4(netaddr)) {
30 		netnum = SRCADR(netaddr);
31 
32 		/*
33 		 * We live in a modern CIDR world where the basement nets, which
34 		 * used to be class A, are now probably associated with each
35 		 * host address. So, for class-A nets, all bits are significant.
36 		 */
37 		if (IN_CLASSC(netnum))
38 			netnum &= IN_CLASSC_NET;
39 		else if (IN_CLASSB(netnum))
40 			netnum &= IN_CLASSB_NET;
41 
42 		SET_ADDR4(netaddr, netnum);
43 
44 	} else if (IS_IPV6(netaddr))
45 		/* assume the typical /64 subnet size */
46 		zero_mem(&NSRCADR6(netaddr)[8], 8);
47 #ifdef DEBUG
48 	else {
49 		msyslog(LOG_ERR, "netof unknown AF %d", AF(netaddr));
50 		exit(1);
51 	}
52 #endif
53 
54 	return netaddr;
55 }
56