On Fri, Jan 30, 2026 at 04:44:38PM -0500, Jon Maloy wrote:
Add a convenience macro to compute an IPv4 netmask from a prefix length. This simplifies netmask calculations throughout the codebase.
Signed-off-by: Jon Maloy
Reviewed-by: David Gibson
--- conf.c | 2 +- dhcp.c | 2 +- ip.h | 2 ++ 3 files changed, 4 insertions(+), 2 deletions(-)
diff --git a/conf.c b/conf.c index 98d5d17..5188c02 100644 --- a/conf.c +++ b/conf.c @@ -1147,7 +1147,7 @@ static void conf_print(const struct ctx *c) if (!c->no_dhcp) { uint32_t mask;
- mask = htonl(0xffffffff << (32 - c->ip4.prefix_len)); + mask = IN4_MASK(c->ip4.prefix_len);
info("DHCP:"); info(" assign: %s", diff --git a/dhcp.c b/dhcp.c index 6b9c2e3..c552f01 100644 --- a/dhcp.c +++ b/dhcp.c @@ -404,7 +404,7 @@ int dhcp(const struct ctx *c, struct iov_tail *data)
info(" from %s", eth_ntop(m->chaddr, macstr, sizeof(macstr)));
- mask.s_addr = htonl(0xffffffff << (32 - c->ip4.prefix_len)); + mask.s_addr = IN4_MASK(c->ip4.prefix_len); memcpy(opts[1].s, &mask, sizeof(mask)); memcpy(opts[3].s, &c->ip4.guest_gw, sizeof(c->ip4.guest_gw)); memcpy(opts[54].s, &c->ip4.our_tap_addr, sizeof(c->ip4.our_tap_addr)); diff --git a/ip.h b/ip.h index bd28640..c829d84 100644 --- a/ip.h +++ b/ip.h @@ -17,6 +17,8 @@ (ntohl(((struct in_addr *)(a))->s_addr) >> IN_CLASSA_NSHIFT == IN_LOOPBACKNET) #define IN4_IS_ADDR_MULTICAST(a) \ (IN_MULTICAST(ntohl(((struct in_addr *)(a))->s_addr))) +#define IN4_MASK(prefix_len) \ + (htonl(0xffffffff << (128 - (prefix_len)))) #define IN4_ARE_ADDR_EQUAL(a, b) \ (((struct in_addr *)(a))->s_addr == ((struct in_addr *)b)->s_addr) #define IN4ADDR_LOOPBACK_INIT \ -- 2.52.0
-- David Gibson (he or they) | I'll have my music baroque, and my code david AT gibson.dropbear.id.au | minimalist, thank you, not the other way | around. http://www.ozlabs.org/~dgibson