From: hannes Date: Sun, 22 Dec 2002 01:26:48 +0000 (+0000) Subject: add mask2plen function to util.c X-Git-Tag: tcpdump-3.8-bp~249 X-Git-Url: https://git.tcpdump.org/tcpdump/commitdiff_plain/a4d961cbef40571aef1bc63281e3c544c6019de8 add mask2plen function to util.c --- diff --git a/interface.h b/interface.h index 647403de..9d2a41fc 100644 --- a/interface.h +++ b/interface.h @@ -18,7 +18,7 @@ * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * - * @(#) $Header: /tcpdump/master/tcpdump/interface.h,v 1.203 2002-12-19 09:39:10 guy Exp $ (LBL) + * @(#) $Header: /tcpdump/master/tcpdump/interface.h,v 1.204 2002-12-22 01:26:48 hannes Exp $ (LBL) */ #ifndef tcpdump_interface_h @@ -158,6 +158,7 @@ extern void relts_print(int); extern int fn_print(const u_char *, const u_char *); extern int fn_printn(const u_char *, u_int, const u_char *); extern const char *tok2str(const struct tok *, const char *, int); +extern int mask2plen(u_int32_t); extern char *bittok2str(const struct tok *, const char *, int); extern const char *tok2strary_internal(const char **, int, const char *, int); #define tok2strary(a,f,i) tok2strary_internal(a, sizeof(a)/sizeof(a[0]),f,i) diff --git a/util.c b/util.c index 84d4a076..a1c9f094 100644 --- a/util.c +++ b/util.c @@ -21,7 +21,7 @@ #ifndef lint static const char rcsid[] = - "@(#) $Header: /tcpdump/master/tcpdump/util.c,v 1.81 2002-11-07 20:07:58 hannes Exp $ (LBL)"; + "@(#) $Header: /tcpdump/master/tcpdump/util.c,v 1.82 2002-12-22 01:26:49 hannes Exp $ (LBL)"; #endif #ifdef HAVE_CONFIG_H @@ -311,6 +311,37 @@ tok2strary_internal(register const char **lp, int n, register const char *fmt, return (buf); } +/* + * Convert a 32-bit netmask to prefixlen if possible + * the function returns the prefix-len; if plen == -1 + * then conversion was not possible; + */ + +int +mask2plen (u_int32_t mask) +{ + u_int32_t bitmasks[33] = { + 0x00000000, + 0x80000000, 0xc0000000, 0xe0000000, 0xf0000000, + 0xf8000000, 0xfc000000, 0xfe000000, 0xff000000, + 0xff800000, 0xffc00000, 0xffe00000, 0xfff00000, + 0xfff80000, 0xfffc0000, 0xfffe0000, 0xffff0000, + 0xffff8000, 0xffffc000, 0xffffe000, 0xfffff000, + 0xfffff800, 0xfffffc00, 0xfffffe00, 0xffffff00, + 0xffffff80, 0xffffffc0, 0xffffffe0, 0xfffffff0, + 0xfffffff8, 0xfffffffc, 0xfffffffe, 0xffffffff + }; + int prefix_len = 33; + + /* lets see if we can transform the mask into a prefixlen */ + while (prefix_len >= 0) { + if (bitmasks[prefix_len] == mask) + break; + prefix_len--; + } + return (prefix_len); +} + /* VARARGS */ void error(const char *fmt, ...)