base-files: ipcalc.sh: fail when network is too small
[openwrt/openwrt.git] / package / base-files / files / bin / ipcalc.sh
1 #!/bin/sh
2
3 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 function compl32(v) {
26 ret=xor(v, 0xffffffff)
27 return ret
28 }
29
30 BEGIN {
31 slpos=index(ARGV[1],"/")
32 if (slpos == 0) {
33 ipaddr=ip2int(ARGV[1])
34 dotpos=index(ARGV[2],".")
35 if (dotpos == 0)
36 netmask=compl32(2**(32-int(ARGV[2]))-1)
37 else
38 netmask=ip2int(ARGV[2])
39 } else {
40 ipaddr=ip2int(substr(ARGV[1],0,slpos-1))
41 netmask=compl32(2**(32-int(substr(ARGV[1],slpos+1)))-1)
42 ARGV[4]=ARGV[3]
43 ARGV[3]=ARGV[2]
44 }
45
46 network=and(ipaddr,netmask)
47 prefix=32-bitcount(compl32(netmask))
48 broadcast=or(network,compl32(netmask))
49
50 print "IP="int2ip(ipaddr)
51 print "NETMASK="int2ip(netmask)
52 print "BROADCAST="int2ip(broadcast)
53 print "NETWORK="int2ip(network)
54 print "PREFIX="prefix
55
56 # range calculations:
57 # ipcalc <ip> <netmask> <start> <num>
58
59 if (ARGC <= 3)
60 exit(0)
61
62 start=or(network,and(ip2int(ARGV[3]),compl32(netmask)))
63 limit=network+1
64 if (start<limit) start=limit
65 if (start==ipaddr) start=ipaddr+1
66
67 end=start+ARGV[4]
68 limit=or(network,compl32(netmask))-1
69 if (end>limit) end=limit
70 if (end==ipaddr) end=ipaddr-1
71
72 if (start>end) {
73 print "network ("int2ip(network)"/"prefix") too small" > "/dev/stderr"
74 exit(1)
75 }
76
77 if (ipaddr > start && ipaddr < end) {
78 print "ipaddr inside range" > "/dev/stderr"
79 exit(1)
80 }
81
82 print "START="int2ip(start)
83 print "END="int2ip(end)
84 }
85 EOF