base-files: /usr/lib/common.awk is only used by /bin/ipcalc.sh, move the code there
[openwrt.git] / package / base-files / files / bin / ipcalc.sh
1 #!/bin/sh
2
3 awk -f /usr/lib/common.awk -f - $* <<EOF
4 function bitcount(c) {
5         c=and(rshift(c, 1),0x55555555)+and(c,0x55555555)
6         c=and(rshift(c, 2),0x33333333)+and(c,0x33333333)
7         c=and(rshift(c, 4),0x0f0f0f0f)+and(c,0x0f0f0f0f)
8         c=and(rshift(c, 8),0x00ff00ff)+and(c,0x00ff00ff)
9         c=and(rshift(c,16),0x0000ffff)+and(c,0x0000ffff)
10         return c
11 }
12
13 function ip2int(ip) {
14         for (ret=0,n=split(ip,a,"\."),x=1;x<=n;x++) ret=or(lshift(ret,8),a[x]) 
15         return ret
16 }
17
18 function int2ip(ip,ret,x) {
19         ret=and(ip,255)
20         ip=rshift(ip,8)
21         for(;x<3;ret=and(ip,255)"."ret,ip=rshift(ip,8),x++);
22         return ret
23 }
24
25 BEGIN {
26         ipaddr=ip2int(ARGV[1])
27         netmask=ip2int(ARGV[2])
28         network=and(ipaddr,netmask)
29         broadcast=or(network,compl(netmask))
30         
31         start=or(network,and(ip2int(ARGV[3]),compl(netmask)))
32         limit=network+1
33         if (start<limit) start=limit
34         
35         end=start+ARGV[4]
36         limit=or(network,compl(netmask))-1
37         if (end>limit) end=limit
38
39         print "IP="int2ip(ipaddr)
40         print "NETMASK="int2ip(netmask)
41         print "BROADCAST="int2ip(broadcast)
42         print "NETWORK="int2ip(network)
43         print "PREFIX="32-bitcount(compl(netmask))
44         
45         # range calculations:
46         # ipcalc <ip> <netmask> <start> <num>
47         
48         if (ARGC > 3) {
49                 print "START="int2ip(start)
50                 print "END="int2ip(end)
51         }
52 }
53 EOF