On Sun, 15 Mar 2015 19:01:43 PDT Victor <
dsgnv...@gmail.com> wrote:
>
> I'm looking for a Go lib, code snippet or an advice on "calculating" one or
> more CIDR from two ip addresses.
Here's some old C code that may help. Can't be bothered to
reimplement in Go but the key idea is to use a progressively
shorter mask, as long as the masked range starts with a1 and
doesn't go past a2. Print this range & set a1 to an address
just past the range. Repeat until a2 is covered.
#include <stdio.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int c, char** v) {
char* addr1 = c > 1? v[1] : "0.0.0.1";
char* addr2 = c > 2? v[2] : "255.255.255.254";
in_addr_t a1 = ntohl(inet_addr(addr1));
in_addr_t a2 = ntohl(inet_addr(addr2));
while (a2 >= a1) {
struct in_addr a;
in_addr_t m = ~0;
int l = 32;
while (m > 0) {
in_addr_t m1 = m << 1;
if ((a1&m1) != a1 || (a1|~m1) > a2)
break;
m = m1;
l--;
}
a.s_addr = htonl(a1);
printf("%s/%d\n", inet_ntoa(a), l);
a1 |= ~m;
if (a1 + 1 < a1)
break;
a1 += 1;
}
return 0;
}