1 /**************************************************************************************************
2 	$Id: cidr.c,v 1.6 2005/04/20 16:49:11 bboy Exp $
3 
4 	Copyright (C) 2002-2005  Don Moore <bboy@bboy.net>
5 
6 	This program is free software; you can redistribute it and/or modify
7 	it under the terms of the GNU General Public License as published by
8 	the Free Software Foundation; either version 2 of the License, or
9 	(at Your option) any later version.
10 
11 	This program is distributed in the hope that it will be useful,
12 	but WITHOUT ANY WARRANTY; without even the implied warranty of
13 	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 	GNU General Public License for more details.
15 
16 	You should have received a copy of the GNU General Public License
17 	along with this program; if not, write to the Free Software
18 	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19 **************************************************************************************************/
20 
21 #include "mydnsutil.h"
22 
23 
24 /**************************************************************************************************
25 	IN_CIDR
26 	Checks to see if the specified IP address is within the specified CIDR range.
27 	XXX: Fix to work with IPv6
28 	Returns 1 if so, 0 if not.
29 **************************************************************************************************/
30 int
in_cidr(char * cidr,struct in_addr ip)31 in_cidr(char *cidr, struct in_addr ip) {
32   unsigned int tmp[8];
33   struct in_addr network, netmask;
34 
35   network.s_addr = 0;
36   netmask.s_addr = 0;
37 
38   if (sscanf(cidr, "%u.%u.%u.%u/%u.%u.%u.%u",
39 	     &tmp[0], &tmp[1], &tmp[2], &tmp[3], &tmp[4], &tmp[5], &tmp[6], &tmp[7]) == 8) {
40     network.s_addr = htonl((tmp[0] << 24) + (tmp[1] << 16) + (tmp[2] << 8) + tmp[3]);
41     netmask.s_addr = htonl((tmp[4] << 24) + (tmp[5] << 16) + (tmp[6] << 8) + tmp[7]);
42   } else if (sscanf(cidr, "%u.%u.%u.%u/%u", &tmp[0], &tmp[1], &tmp[2], &tmp[3], &tmp[4]) == 5) {
43     network.s_addr = htonl((tmp[0] << 24) + (tmp[1] << 16) + (tmp[2] << 8) + tmp[3]);
44     while (tmp[4] > 0) {
45       netmask.s_addr = (netmask.s_addr >> 1) + 0x80000000;
46       tmp[4]--;
47     }
48     netmask.s_addr = htonl(netmask.s_addr);
49   } else return (0);
50 
51   return ((ip.s_addr & netmask.s_addr) == (network.s_addr & netmask.s_addr));
52 }
53 /*--- in_cidr() ---------------------------------------------------------------------------------*/
54 
55 /* vi:set ts=3: */
56