converted to git
[tridge/junkcode.git] / matching_bits.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <signal.h>
5 #include <math.h>
6 #include <errno.h>
7 #include <sys/socket.h>
8 #include <netdb.h>
9 #include <unistd.h>
10 #include <strings.h>
11 #include <sys/time.h>
12 #include <sys/types.h>
13 #include <netinet/in.h>
14 #include <netinet/tcp.h>
15 #include <netinet/in_systm.h>
16 #include <netinet/ip.h>
17
18 typedef unsigned char uchar;
19
20 /****************************************************************************
21 return the number of bits that match between two 4 character buffers
22   ***************************************************************************/
23 int matching_quad_bits(uchar *p1, uchar *p2)
24 {
25         int i, j, ret = 0;
26         for (i=0; i<4; i++) {
27                 if (p1[i] != p2[i]) break;
28                 ret += 8;
29         }
30
31         if (i==4) return ret;
32
33         for (j=0; j<8; j++) {
34                 if ((p1[i] & (1<<(7-j))) != (p2[i] & (1<<(7-j)))) break;
35                 ret++;
36         }       
37         
38         return ret;
39 }
40
41
42 int main(int argc, char *argv[])
43 {
44         struct in_addr ip1, ip2;
45
46         if (argc < 3) {
47                 printf("Usage: matching_bits IP1 IP2\n");
48                 exit(1);
49         }
50
51         inet_aton(argv[1], &ip1);
52         inet_aton(argv[2], &ip2);
53
54         printf("%d\n", matching_quad_bits((uchar *)&ip1.s_addr, (uchar *)&ip2.s_addr));
55         return 0;
56 }