11
gf_is_ip_in_net(const char *network, const char *ip_str)
13
/* A buffer big enough for any socket address. */
14
uint8_t net_buff[sizeof(struct sockaddr_storage) + 1];
15
uint8_t ip_buff[sizeof(struct sockaddr_storage) + 1];
21
if (strchr(network, ':'))
23
else if (strchr(network, '.'))
29
size = inet_net_pton(family, network, net_buff, sizeof(net_buff));
31
fprintf(stderr, "inet_net_pton: %s\n", strerror(errno));
35
ret = inet_pton(family, ip_str, &ip_buff);
37
fprintf(stderr, "inet_pton: %s\n", strerror(errno));
41
mask = (0xff00 >> (size & 7)) & 0xff;
43
net_buff[size] &= mask;
44
ip_buff[size] &= mask;
46
return memcmp(net_buff, ip_buff, size + 1) == 0;
52
main(int argc, char *argv[])
55
fprintf(stderr, "Syntax: ip_in_cidr <subnet_address> <ip_address>");
58
char *subnet_str = argv[1];
59
char *ip_addr = argv[2];
62
result = gf_is_ip_in_net(subnet_str, ip_addr);
64
fprintf(stdout, "YES\n");
66
fprintf(stdout, "NO\n");