capt_get_packet(): check for key press only every 20ms
[iptraf-ng.git] / src / cidr.c
blob768dd0c91fc1ac2f8cf014bfc2ff8254f45a8612
1 /* For terms of usage/redistribution/modification see the LICENSE file */
2 /* For authors and contributors see the AUTHORS file */
4 #include "iptraf-ng-compat.h"
6 // TODO: full rewrite
8 /*
9 * Returns a binary subnet mask based on the number of mask bits. The
10 * dotted-decimal notation may be obtained with inet_ntoa.
12 unsigned long cidr_get_mask(unsigned int maskbits)
14 struct in_addr mask;
16 if (maskbits == 0)
17 return 0;
19 inet_aton("255.255.255.255", &mask);
20 mask.s_addr = htonl(mask.s_addr << (32 - maskbits));
22 return mask.s_addr;
26 * Returns a subnet mask in dotted-decimal notation given the number of
27 * 1-bits in the mask.
29 char *cidr_get_quad_mask(unsigned int maskbits)
31 struct in_addr addr;
33 addr.s_addr = cidr_get_mask(maskbits);
34 return inet_ntoa(addr);
38 * Returns the number of 1-bits in the given binary subnet mask in
39 * network byte order.
41 unsigned int cidr_get_maskbits(unsigned long mask)
43 unsigned int i = 32;
45 if (mask == 0)
46 return 0;
48 mask = ntohl(mask);
49 while (mask % 2 == 0) {
50 mask >>= 1;
51 i--;
54 return i;
58 * Parse and cut off mask from CIDR-style address/mask string. In case of
59 * absent or invalid input in the mask, 255 is returned in *maskbits
60 * (255 is invalid for an IPv4 address).
62 void cidr_split_address(char *cidr_addr, unsigned int *maskbits)
64 char *slashptr = strchr(cidr_addr, '/');
65 if (slashptr == NULL) {
66 *maskbits = 255;
67 return;
71 * Cut out the mask part and move past the slash
73 *slashptr = '\0';
74 slashptr++;
76 if (*slashptr != '\0') {
77 unsigned long val;
78 char *endptr;
80 val = strtoul(slashptr, &endptr, 10);
81 if (val > UINT_MAX)
82 val = UINT_MAX;
83 *maskbits = (unsigned int)val;
84 if (*endptr != '\0')
85 *maskbits = 255;
86 } else
87 *maskbits = 255;
89 return;