1 /*        $NetBSD: netof.c,v 1.6 2024/08/18 20:47:13 christos Exp $   */
2 
3 /*
4  * netof - return the net address part of an ip address in a sockaddr_u 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 /*
17  * Return the network portion of a host address.  Used by ntp_io.c
18  * findbcastinter() to find a multicast/broadcast interface for
19  * a given remote address.  Note static storage is used, with room
20  * for only two addresses, which is all that is needed at present.
21  *
22  */
23 sockaddr_u *
netof(sockaddr_u * hostaddr)24 netof(
25           sockaddr_u *hostaddr
26           )
27 {
28           static sockaddr_u   netofbuf[2];
29           static int                    next_netofbuf;
30           u_int32                       netnum;
31           sockaddr_u *                  netaddr;
32 
33           netaddr = &netofbuf[next_netofbuf];
34           next_netofbuf = (next_netofbuf + 1) % COUNTOF(netofbuf);
35 
36           memcpy(netaddr, hostaddr, sizeof(*netaddr));
37 
38           if (IS_IPV4(netaddr)) {
39                     /*
40                      * We live in a modern classless IPv4 world.  Assume /24.
41                      */
42                     netnum = SRCADR(netaddr) & IN_CLASSC_NET;
43                     SET_ADDR4(netaddr, netnum);
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