776b204af89c8658bfca2f35eeb5b1ae76de4194
[platform/upstream/bash.git] / examples / functions / inetaddr
1 #
2 # inet2hex - Internet address conversion, dotted-decimal to hex
3 #
4 inet2hex ()
5 {
6         local IFS
7
8         IFS=.
9         set -- $1
10
11         if (( $# != 4 )); then
12                 echo "inet2hex: incorrect input format: $1" >&2
13                 echo "inet2hex: usage: inet2hex XX.XX.XX.XX" >&2
14                 return 2
15         fi
16   
17         printf "0x%02x%02x%02x%02x\n" $1 $2 $3 $4
18 }
19
20 #
21 # hex2inet - Internet address conversion, hex to dotted-decimal
22 #
23 hex2inet ()
24 {
25         local x1 x2 x3 x4
26
27         case "$1" in
28         0x*)    h=${1#??} ;;
29         *)      h=$1 ;;
30         esac
31
32         if (( ${#h} != 8 )); then
33                 echo "hex2inet: $h not in inet format" >&2
34                 echo "hex2inet: usage: hex2inet [0x]XXXXXXXX" >&2
35                 return 2
36         fi
37
38         x1=$(( 0x${h:0:2} ))
39         x2=$(( 0x${h:2:2} ))
40         x3=$(( 0x${h:4:2} ))
41         x4=$(( 0x${h:6:2} ))
42
43         printf "%d.%d.%d.%d\n" $x1 $x2 $x3 $x4 
44 }