e818e678033266ec1d4be4105e152ff66d53e26d
[openwrt/staging/stintel.git] / package / base-files / files / bin / ipcalc.sh
1 #!/usr/bin/awk -f
2
3 function bitcount(c) {
4 c=and(rshift(c, 1),0x55555555)+and(c,0x55555555)
5 c=and(rshift(c, 2),0x33333333)+and(c,0x33333333)
6 c=and(rshift(c, 4),0x0f0f0f0f)+and(c,0x0f0f0f0f)
7 c=and(rshift(c, 8),0x00ff00ff)+and(c,0x00ff00ff)
8 c=and(rshift(c,16),0x0000ffff)+and(c,0x0000ffff)
9 return c
10 }
11
12 function ip2int(ip) {
13 for (ret=0,n=split(ip,a,"\."),x=1;x<=n;x++) ret=or(lshift(ret,8),a[x])
14 return ret
15 }
16
17 function int2ip(ip,ret,x) {
18 ret=and(ip,255)
19 ip=rshift(ip,8)
20 for(;x<3;ret=and(ip,255)"."ret,ip=rshift(ip,8),x++);
21 return ret
22 }
23
24 function compl32(v) {
25 ret=xor(v, 0xffffffff)
26 return ret
27 }
28
29 BEGIN {
30 slpos=index(ARGV[1],"/")
31 if (slpos == 0) {
32 ipaddr=ip2int(ARGV[1])
33 dotpos=index(ARGV[2],".")
34 if (dotpos == 0)
35 netmask=compl32(2**(32-int(ARGV[2]))-1)
36 else
37 netmask=ip2int(ARGV[2])
38 } else {
39 ipaddr=ip2int(substr(ARGV[1],0,slpos-1))
40 netmask=compl32(2**(32-int(substr(ARGV[1],slpos+1)))-1)
41 ARGV[4]=ARGV[3]
42 ARGV[3]=ARGV[2]
43 }
44
45 network=and(ipaddr,netmask)
46 prefix=32-bitcount(compl32(netmask))
47 broadcast=or(network,compl32(netmask))
48
49 print "IP="int2ip(ipaddr)
50 print "NETMASK="int2ip(netmask)
51 print "BROADCAST="int2ip(broadcast)
52 print "NETWORK="int2ip(network)
53 print "PREFIX="prefix
54
55 # range calculations:
56 # ipcalc <ip> <netmask> <start> <num>
57
58 if (ARGC <= 3)
59 exit(0)
60
61 start=or(network,and(ip2int(ARGV[3]),compl32(netmask)))
62 limit=network+1
63 if (start<limit) start=limit
64 if (start==ipaddr) start=ipaddr+1
65
66 end=start+ARGV[4]
67 limit=or(network,compl32(netmask))-1
68 if (end>limit) end=limit
69 if (end==ipaddr) end=ipaddr-1
70
71 if (start>end) {
72 print "network ("int2ip(network)"/"prefix") too small" > "/dev/stderr"
73 exit(1)
74 }
75
76 if (ipaddr > start && ipaddr < end) {
77 print "ipaddr inside range" > "/dev/stderr"
78 exit(1)
79 }
80
81 print "START="int2ip(start)
82 print "END="int2ip(end)
83 }