1
+ #! /bin/bash
2
+
3
+
4
+ # converts IPv4 as "A.B.C.D" to integer
5
+ ip4_to_int () {
6
+ IFS=. read -r i j k l << EOF
7
+ $1
8
+ EOF
9
+ echo $(( (i << 24 ) + (j << 16 ) + (k << 8 ) + l ))
10
+ }
11
+
12
+ # converts interger to IPv4 as "A.B.C.D"
13
+ int_to_ip4 () {
14
+ echo " $(( ($1 >> 24 ) % 256 )) .$(( ($1 >> 16 ) % 256 )) .$(( ($1 >> 8 ) % 256 )) .$(( $1 % 256 )) "
15
+ }
16
+
17
+ # returns the ip part of an CIDR
18
+ cidr_ip () {
19
+ IFS=/ read -r ip _ << EOF
20
+ $1
21
+ EOF
22
+ echo $ip
23
+ }
24
+
25
+ # returns the prefix part of an CIDR
26
+ cidr_prefix () {
27
+ IFS=/ read -r _ prefix << EOF
28
+ $1
29
+ EOF
30
+ echo $prefix
31
+ }
32
+
33
+ # returns net mask in numberic from prefix size
34
+ netmask_of_prefix () {
35
+ echo $(( 4294967295 ^ (1 << (32 - $1 )) - 1))
36
+ }
37
+
38
+ # returns default gateway address (network address + 1) from CIDR
39
+ cidr_default_gw () {
40
+ ip=$( ip4_to_int $( cidr_ip $1 ) )
41
+ prefix=$( cidr_prefix $1 )
42
+ netmask=$( netmask_of_prefix $prefix )
43
+ gw=$(( ip & netmask + 1 ))
44
+ int_to_ip4 $gw
45
+ }
46
+
47
+ # returns default gateway address (broadcast address - 1) from CIDR
48
+ cidr_default_gw_2 () {
49
+ ip=$( ip4_to_int $( cidr_ip $1 ) )
50
+ prefix=$( cidr_prefix $1 )
51
+ netmask=$( netmask_of_prefix $prefix )
52
+ broadcast=$(( (4294967295 - netmask) | ip))
53
+ int_to_ip4 $(( broadcast - 1 ))
54
+ }
55
+
56
+
57
+ ip4_to_int 192.168.0.1
58
+ # => 3232235521
59
+
60
+ int_to_ip4 3232235521
61
+ # => 192.168.0.1
62
+
63
+
64
+ # network address
65
+ ip=$( ip4_to_int 172.16.10.20)
66
+ netmask=$( ip4_to_int 255.255.252.0)
67
+ int_to_ip4 $(( ip & netmask))
68
+ # => 172.16.8.0
69
+
70
+
71
+ # broadcast address
72
+ ip=$( ip4_to_int 172.16.10.20)
73
+ netmask=$( ip4_to_int 255.255.252.0)
74
+ int_to_ip4 $(( (ip & netmask) + 1 ))
75
+ # => 172.16.8.1
76
+
77
+
78
+ cidr_ip " 172.16.0.10/22"
79
+ # => 172.16.0.10
80
+
81
+ cidr_prefix " 172.16.0.10/22"
82
+ # => 22
83
+
84
+ netmask_of_prefix 8
85
+ # => 4278190080
86
+
87
+
88
+ cidr_default_gw 192.168.10.1/24
89
+ # => 192.168.10.1
90
+ cidr_default_gw 192.168.10.1/16
91
+ # => 192.168.0.1
92
+ cidr_default_gw 172.17.18.19/20
93
+ # => 172.17.16.1
94
+
95
+
96
+ cidr_default_gw_2 192.168.10.1/24
97
+ # => 192.168.10.254
98
+ cidr_default_gw_2 192.168.10.1/16
99
+ # => 192.168.255.254
100
+ cidr_default_gw_2 172.17.18.19/20
101
+ # => 172.17.31.254
0 commit comments