-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathipv4subnets.c
100 lines (91 loc) · 1.69 KB
/
ipv4subnets.c
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include "cll1-0.6.2.h"
/* ====== iptables indexes are used to reduce complexity to log(N) ===== */
char *very_ugly_ipv4_code(char *inip, int bitmask, int format_as_chainname)
{
int dot=0, n;
char *ip,*outip,*outptr,*fmt;
duplicate(inip,ip);
/* debug printf("(%s,%d) -> ",ip,bitmask); */
if(ip && *ip && bitmask>=0 && bitmask<=32)
{
string(outip,strlen(ip)+10); /* assertion: 10>strlen("_%d_%d") */
}
else
{
/* should never exit here */
return "undefined";
}
outptr=outip;
while(ip && *ip)
{
if(*ip=='.')
{
if(dot<(bitmask/8-1))
{
if(format_as_chainname)
{
*outptr='_';
}
else
{
*outptr='.';
}
outptr++;
dot++;
}
else
{
char *cutdot=strchr(ip+1,'.'); /*for bitmask<24*/
if(cutdot)
{
*cutdot = '\0';
}
if(format_as_chainname)
{
fmt = "_%d_%d";
}
else
{
fmt = ".%d";
}
if(bitmask%8)
{
n = atoi(ip+1)-atoi(ip+1)%(1<<(8-bitmask%8));
}
else
{
n = 0;
}
/*debug printf("%d/%d => [_%d_%d]\n",atoi(ip+1),bitmask,n,bitmask); */
sprintf(outptr,fmt,n,bitmask);
if(!format_as_chainname)
{
while(bitmask<24)
{
strcat(outip,".0");
bitmask+=8;
}
}
/* debug printf("[%s]\n",outip); */
return outip;
}
}
else
{
*outptr=*ip;
outptr++;
}
ip++;
}
/*should never exit here*/
*outptr='\0';
return outip;
}
char *index_id(char *ip, int bitmask)
{
return very_ugly_ipv4_code(ip,bitmask,1);
}
char *subnet_id(char *ip, int bitmask)
{
return very_ugly_ipv4_code(ip,bitmask,0);
}