9b5e5accdca8ca1c4198ae573240eb57e7e70448
[openwrt/openwrt.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 ret=0
14 n=split(ip,a,"\\.")
15 for (x=1;x<=n;x++)
16 ret=or(lshift(ret,8),a[x])
17 return ret
18 }
19
20 function int2ip(ip,ret,x) {
21 ret=and(ip,255)
22 ip=rshift(ip,8)
23 for(;x<3;x++) {
24 ret=and(ip,255)"."ret
25 ip=rshift(ip,8)
26 }
27 return ret
28 }
29
30 function compl32(v) {
31 ret=xor(v, 0xffffffff)
32 return ret
33 }
34
35 BEGIN {
36 slpos=index(ARGV[1],"/")
37 if (slpos != 0) {
38 # rearrange arguments to not use compound notation
39 ARGV[4]=ARGV[3]
40 ARGV[3]=ARGV[2]
41 ARGV[2]=substr(ARGV[1],slpos+1)
42 ARGV[1]=substr(ARGV[1],0,slpos-1)
43 }
44 ipaddr=ip2int(ARGV[1])
45 dotpos=index(ARGV[2],".")
46 if (dotpos == 0)
47 netmask=compl32(2**(32-int(ARGV[2]))-1)
48 else
49 netmask=ip2int(ARGV[2])
50
51 network=and(ipaddr,netmask)
52 prefix=32-bitcount(compl32(netmask))
53
54 print "IP="int2ip(ipaddr)
55 print "NETMASK="int2ip(netmask)
56 print "NETWORK="int2ip(network)
57 if (prefix<=30) {
58 broadcast=or(network,compl32(netmask))
59 print "BROADCAST="int2ip(broadcast)
60 }
61 print "PREFIX="prefix
62
63 # range calculations:
64 # ipcalc <ip> <netmask> <range_start> <range_size>
65
66 if (ARGC <= 3)
67 exit(0)
68
69 if (prefix<=30)
70 limit=network+1
71 else
72 limit=network
73
74 start=or(network,and(ip2int(ARGV[3]),compl32(netmask)))
75 if (start<limit) start=limit
76 if (start==ipaddr) start=ipaddr+1
77
78 if (prefix<=30)
79 limit=or(network,compl32(netmask))-1
80 else
81 limit=or(network,compl32(netmask))
82
83 end=start+ARGV[4]-1
84 if (end>limit) end=limit
85 if (end==ipaddr) end=ipaddr-1
86
87 if (start>end) {
88 print "network ("int2ip(network)"/"prefix") too small" > "/dev/stderr"
89 exit(1)
90 }
91
92 if (ipaddr >= start && ipaddr <= end) {
93 print "warning: ipaddr inside range - this might not be supported in future releases of Openwrt" > "/dev/stderr"
94 # turn this into an error after Openwrt 24 has been released
95 # exit(1)
96 }
97
98 print "START="int2ip(start)
99 print "END="int2ip(end)
100 }