summaryrefslogtreecommitdiff
path: root/src/bin/iplist2cidr.c
blob: f909b625cde73049017ffb5f15a535f6d0d9782d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <stdlib.h>

struct net {
 unsigned int ip;
 unsigned char cidr;
};

#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))

int main(int argc,char *argv[]) {
 short in;
 int maxcidr;
 int i=0,j=0,len=0;
 struct net list[65536];//don't do more than a /16!
 char ips[64];//why not?
 char *cidrs;
 while((in=fgetc(stdin)) != -1) {
  if(in=='\n') {
   ips[i]=0;
   if((cidrs=strchr(ips,'/')) != 0) {
    *cidrs=0;
    cidrs++;
   }
   list[len].ip=htonl(inet_addr(ips));
   list[len].cidr=cidrs?atoi(cidrs):32;
   i=0;
   cidrs=0;
   len++;
   continue;
  }
  ips[i]=in;
  i++;
  if(i>63) {
   printf("your have a line that is TOOO long. stick to IPv4.\n");
   return 0;
  }
 }
 //!!!warning!!! inefficient algo ahead!
 for(i=0;i<len;i++) {
  for(j=0;j<len;j++) {
   if(list[i].cidr == list[j].cidr) {
    if((list[i].ip ^ list[j].ip) >> (32-list[i].cidr) == 1) {
     list[i].cidr--;
     list[j].cidr--;
     list[i].ip &= (0xffffffff << (32-list[i].cidr));
     list[j].ip &= (0xffffffff << (32-list[j].cidr));
     i=-1;//start over!
     j=-1;//start over!
     continue;
    }
   }
   if(list[i].ip == list[j].ip && list[i].cidr != list[j].cidr) {
    list[i].cidr = min(list[i].cidr,list[j].cidr);
    list[j].cidr = min(list[i].cidr,list[j].cidr);
    i=-1;//start over!
    j=-1;//start over!
    continue;
   }
   maxcidr=min(list[i].cidr,list[j].cidr);
   if(list[i].cidr != list[j].cidr) {
    if(list[i].ip >> (32-maxcidr) == list[j].ip >> (32-maxcidr) ) {
     list[i].cidr = min(list[i].cidr,list[j].cidr);
     list[j].cidr = min(list[i].cidr,list[j].cidr);
     list[i].ip &= (0xffffffff << (32-list[i].cidr));
     list[j].ip &= (0xffffffff << (32-list[j].cidr));
     i=-1;//start over!
     j=-1;//start over!
     continue;
    }
   }
  }
 }
 for(i=0;i<len;i++) {
  printf("%d.%d.%d.%d/%d\n",list[i].ip>>24&255,list[i].ip>>16&255,list[i].ip>>8&255,list[i].ip&255,list[i].cidr);
 }
 return 0;
}