0cd6e14f09f7ea92c9b6db72fca936787cb0731f
[openwrt-10.03/.git] / package / base-files / files / bin / ipcalc.sh
1 #!/bin/sh
2
3 awk -f /usr/lib/common.awk -f - $* <<EOF
4 BEGIN {
5         slpos=index(ARGV[1],"/")
6         if (slpos == 0) {
7                 ipaddr=ip2int(ARGV[1])
8                 netmask=ip2int(ARGV[2])
9         } else {
10                 ipaddr=ip2int(substr(ARGV[1],0,slpos-1))
11                 netmask=compl(2**(32-int(substr(ARGV[1],slpos+1)))-1)
12                 ARGV[4]=ARGV[3]
13                 ARGV[3]=ARGV[2]
14         }
15
16         network=and(ipaddr,netmask)
17         broadcast=or(network,compl(netmask))
18
19         start=or(network,and(ip2int(ARGV[3]),compl(netmask)))
20         limit=network+1
21         if (start<limit) start=limit
22
23         end=start+ARGV[4]
24         limit=or(network,compl(netmask))-1
25         if (end>limit) end=limit
26
27         print "IP="int2ip(ipaddr)
28         print "NETMASK="int2ip(netmask)
29         print "BROADCAST="int2ip(broadcast)
30         print "NETWORK="int2ip(network)
31         print "PREFIX="32-bitcount(compl(netmask))
32
33         # range calculations:
34         # ipcalc <ip> <netmask> <start> <num>
35
36         if (ARGC > 3) {
37                 print "START="int2ip(start)
38                 print "END="int2ip(end)
39         }
40 }
41 EOF