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