Check subnet mask's sanity

This commit is contained in:
Joseph C. Lehner 2016-11-19 13:02:29 +01:00
parent fba7aab1bd
commit eda1a2a698
3 changed files with 19 additions and 1 deletions

4
nmrp.c
View file

@ -430,7 +430,9 @@ int nmrp_do(struct nmrpd_args *args)
return 1;
}
if ((ipconf.mask.s_addr = inet_addr(args->ipmask)) == INADDR_NONE) {
ipconf.mask.s_addr = inet_addr(args->ipmask);
if (ipconf.mask.s_addr == INADDR_NONE
|| netmask(bitcount(ipconf.mask.s_addr)) != ipconf.mask.s_addr) {
fprintf(stderr, "Invalid subnet mask '%s'.\n", args->ipmask);
return 1;
}

View file

@ -133,4 +133,6 @@ int ethsock_ip_del(struct ethsock *sock, struct ethsock_ip_undo **undo);
time_t time_monotonic();
char *lltostr(long long ll, int base);
uint32_t bitcount(uint32_t n);
uint32_t netmask(uint32_t count);
#endif

14
util.c
View file

@ -35,3 +35,17 @@ char *lltostr(long long ll, int base)
snprintf(buf, sizeof(buf) - 1, (base == 16 ? "%llx" : (base == 8 ? "%llo" : "%lld")), ll);
return buf;
}
uint32_t bitcount(uint32_t n)
{
uint32_t c;
for (c = 0; n; ++c) {
n &= n - 1;
}
return c;
}
uint32_t netmask(uint32_t count)
{
return htonl(count <= 32 ? 0xffffffff << (32 - count) : 0);
}