30ae48030566706a89fef0f5c5b5d47f94bd9668
[openwrt/openwrt.git] / package / base-files / files / lib / functions / ipv4.sh
1 uint_max=4294967295
2
3 assert_uint32() {
4 local __n="$1"
5
6 if [ -z "$__n" -o -n "${__n//[0-9]/}" ]; then
7 printf "Not a decimal integer (%s)\n" "$__n ">&2
8 return 1
9 fi
10
11 if [ "$__n" -gt $uint_max ]; then
12 printf "Out of range (%s)\n" "$__n" >&2
13 return 1
14 fi
15
16 if [ "$((__n + 0))" != "$__n" ]; then
17 printf "Not normalized notation (%s)\n" "$__n" >&2
18 return 1
19 fi
20
21 return 0
22 }
23
24 bitcount() {
25 local __var="$1" __c="$2"
26 assert_uint32 "$__c" || return 1
27
28 __c=$((((__c >> 1) & 0x55555555) + (__c & 0x55555555)))
29 __c=$((((__c >> 2) & 0x33333333) + (__c & 0x33333333)))
30 __c=$((((__c >> 4) & 0x0f0f0f0f) + (__c & 0x0f0f0f0f)))
31 __c=$((((__c >> 8) & 0x00ff00ff) + (__c & 0x00ff00ff)))
32 __c=$((((__c >> 16) & 0x0000ffff) + (__c & 0x0000ffff)))
33
34 export -- "$__var=$__c"
35 }
36
37 # tedious but portable with busybox's limited shell
38 str2ip() {
39 local __var="$1" __ip="$2" __n __val=0
40
41 case "$__ip" in
42 [0-9].*)
43 __n="${__ip:0:1}"
44 __ip="${__ip:2}"
45 ;;
46 [1-9][0-9].*)
47 __n="${__ip:0:2}"
48 __ip="${__ip:3}"
49 ;;
50 1[0-9][0-9].*|2[0-4][0-9].*|25[0-5].*)
51 __n="${__ip:0:3}"
52 __ip="${__ip:4}"
53 ;;
54 *)
55 printf "Not a dotted quad (%s)\n" "$2" >&2
56 return 1
57 ;;
58 esac
59
60 __val=$((__n << 24))
61
62 case "$__ip" in
63 [0-9].*)
64 __n="${__ip:0:1}"
65 __ip="${__ip:2}"
66 ;;
67 [1-9][0-9].*)
68 __n="${__ip:0:2}"
69 __ip="${__ip:3}"
70 ;;
71 1[0-9][0-9].*|2[0-4][0-9].*|25[0-5].*)
72 __n="${__ip:0:3}"
73 __ip="${__ip:4}"
74 ;;
75 *)
76 printf "Not a dotted quad (%s)\n" "$2" >&2
77 return 1
78 ;;
79 esac
80
81 __val=$((__val + (__n << 16)))
82
83 case "$__ip" in
84 [0-9].*)
85 __n="${__ip:0:1}"
86 __ip="${__ip:2}"
87 ;;
88 [1-9][0-9].*)
89 __n="${__ip:0:2}"
90 __ip="${__ip:3}"
91 ;;
92 1[0-9][0-9].*|2[0-4][0-9].*|25[0-5].*)
93 __n="${__ip:0:3}"
94 __ip="${__ip:4}"
95 ;;
96 *)
97 printf "Not a dotted quad (%s)\n" "$2" >&2
98 return 1
99 ;;
100 esac
101
102 __val=$((__val + (__n << 8)))
103
104 case "$__ip" in
105 [0-9])
106 __n="${__ip:0:1}"
107 __ip="${__ip:1}"
108 ;;
109 [1-9][0-9])
110 __n="${__ip:0:2}"
111 __ip="${__ip:2}"
112 ;;
113 1[0-9][0-9]|2[0-4][0-9]|25[0-5])
114 __n="${__ip:0:3}"
115 __ip="${__ip:3}"
116 ;;
117 *)
118 printf "Not a dotted quad (%s)\n" "$2" >&2
119 return 1
120 ;;
121 esac
122
123 __val=$((__val + __n))
124
125 if [ -n "$__ip" ]; then
126 printf "Not a dotted quad (%s)\n" "$2" >&2
127 return 1
128 fi
129
130 export -- "$__var=$__val"
131 return 0
132 }
133
134 ip2str() {
135 local __var="$1" __n="$2"
136 assert_uint32 "$__n" || return 1
137
138 export -- "$__var=$((__n >> 24)).$(((__n >> 16) & 255)).$(((__n >> 8) & 255)).$((__n & 255))"
139 }
140