From 70473a5f8c56d8ec2e837b9b66443dc252b24da9 Mon Sep 17 00:00:00 2001 From: Thierry Fournier Date: Wed, 17 Feb 2016 17:12:14 +0100 Subject: [PATCH] MINOR: common: mask conversion Add function which converts network mask from bit length form to struct in*_addr form. --- include/common/standard.h | 10 ++++++++++ src/standard.c | 31 +++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/include/common/standard.h b/include/common/standard.h index a66317171..9abdb0643 100644 --- a/include/common/standard.h +++ b/include/common/standard.h @@ -832,6 +832,16 @@ static inline int set_host_port(struct sockaddr_storage *addr, int port) return 0; } +/* Convert mask from bit length form to in_addr form. + * This function never fails. + */ +void len2mask4(int len, struct in_addr *addr); + +/* Convert mask from bit length form to in6_addr form. + * This function never fails. + */ +void len2mask6(int len, struct in6_addr *addr); + /* Return true if IPv4 address is part of the network */ extern int in_net_ipv4(struct in_addr *addr, struct in_addr *mask, struct in_addr *net); diff --git a/src/standard.c b/src/standard.c index f4da01bc2..30883d759 100644 --- a/src/standard.c +++ b/src/standard.c @@ -1002,6 +1002,37 @@ int cidr2dotted(int cidr, struct in_addr *mask) { return 1; } +/* Convert mask from bit length form to in_addr form. + * This function never fails. + */ +void len2mask4(int len, struct in_addr *addr) +{ + if (len >= 32) { + addr->s_addr = 0xffffffff; + return; + } + if (len <= 0) { + addr->s_addr = 0x00000000; + return; + } + addr->s_addr = 0xffffffff << (32 - len); + addr->s_addr = htonl(addr->s_addr); +} + +/* Convert mask from bit length form to in6_addr form. + * This function never fails. + */ +void len2mask6(int len, struct in6_addr *addr) +{ + len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */ + len -= 32; + len2mask4(len, (struct in_addr *)&addr->s6_addr[4]); + len -= 32; + len2mask4(len, (struct in_addr *)&addr->s6_addr[8]); + len -= 32; + len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */ +} + /* * converts to two struct in_addr* which must be pre-allocated. * The format is "addr[/mask]", where "addr" cannot be empty, and mask