From: Thierry Fournier Date: Wed, 17 Feb 2016 16:12:14 +0000 (+0100) Subject: MINOR: common: mask conversion X-Git-Tag: v1.7-dev2~84 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=70473a5f8c56d8ec2e837b9b66443dc252b24da9;p=thirdparty%2Fhaproxy.git MINOR: common: mask conversion Add function which converts network mask from bit length form to struct in*_addr form. --- diff --git a/include/common/standard.h b/include/common/standard.h index a66317171a..9abdb06439 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 f4da01bc2c..30883d759f 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