xref: /freebsd/contrib/ntp/libntp/netof.c (revision b64c5a0ace59af62eff52bfe110a521dc73c937b)
1 /*
2  * netof - return the net address part of an ip address in a sockaddr_u 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 /*
15  * Return the network portion of a host address.  Used by ntp_io.c
16  * findbcastinter() to find a multicast/broadcast interface for
17  * a given remote address.  Note static storage is used, with room
18  * for only two addresses, which is all that is needed at present.
19  *
20  */
21 sockaddr_u *
22 netof(
23 	sockaddr_u *hostaddr
24 	)
25 {
26 	static sockaddr_u	netofbuf[2];
27 	static int		next_netofbuf;
28 	u_int32			netnum;
29 	sockaddr_u *		netaddr;
30 
31 	netaddr = &netofbuf[next_netofbuf];
32 	next_netofbuf = (next_netofbuf + 1) % COUNTOF(netofbuf);
33 
34 	memcpy(netaddr, hostaddr, sizeof(*netaddr));
35 
36 	if (IS_IPV4(netaddr)) {
37 		/*
38 		 * We live in a modern classless IPv4 world.  Assume /24.
39 		 */
40 		netnum = SRCADR(netaddr) & IN_CLASSC_NET;
41 		SET_ADDR4(netaddr, netnum);
42 	} else if (IS_IPV6(netaddr))
43 		/* assume the typical /64 subnet size */
44 		zero_mem(&NSRCADR6(netaddr)[8], 8);
45 #ifdef DEBUG
46 	else {
47 		msyslog(LOG_ERR, "netof unknown AF %d", AF(netaddr));
48 		exit(1);
49 	}
50 #endif
51 
52 	return netaddr;
53 }
54