1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
| #!/bin/bash
IPPattern="(\<([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\>\.){3}\<([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\>"
maskPattern="[1-9]|[12][0-9]|3[01]"
while :
do
echo -e -n "Please input a legal IP address [such as 192.168.1.1/16]: "
read userInput
IPMask=`echo $userInput | egrep "$IPPattern/$maskPattern"`
#Such as 192.168.1.1/24
if [ -z "$IPMask" ] ;then
echo "Please input the right format. [such as 192.168.1.1/1-31] "
continue
fi
IPAddr=`echo $IPMask | cut -d/ -f1`
IPType[1]=`echo $IPAddr | cut -d. -f1`
IPType[2]=`echo $IPAddr | cut -d. -f2`
IPType[3]=`echo $IPAddr | cut -d. -f3`
IPType[4]=`echo $IPAddr | cut -d. -f4`
mask=`echo $IPMask | cut -d/ -f2`
echo "IP address is ${IPType[1]}*${IPType[2]}*${IPType[3]}*${IPType[4]} , Mask is $mask ."
((IPHex[1]=IPType[1]<<24))
((IPHex[2]=IPType[2]<<16))
((IPHex[3]=IPType[3]<<8))
((IPHex[4]=IPType[4]))
#192 c0 ; 1 1 1
((iph=${IPHex[1]}+${IPHex[2]}+${IPHex[3]}+${IPHex[4]}))
#echo $iph
#0xffffffff
#declare -i strMask1=4294967295
declare -i strMask1=0xffffffff
#echo $strMask1
((strMask1=strMask1<<(32-mask) & 0xffffffff))
#echo $strMask1
((strMask2=~strMask1))
#echo $strMask2
((networkAddr=iph & strMask1))
((bcastAddr= (iph | strMask2) & 0xffffffff))
#echo $networkAddr | awk '{printf "%x\n",$0}'
#echo $bcastAddr | awk '{printf "%x\n",$0}'
((IPHex[1]=networkAddr>>24 & 0x000000ff))
((IPHex[2]=networkAddr>>16 & 0x000000ff))
((IPHex[3]=networkAddr>>8 & 0x000000ff))
((IPHex[4]=networkAddr & 0x000000ff))
echo -e "Network Address : ${IPHex[1]}.${IPHex[2]}.${IPHex[3]}.${IPHex[4]}"
((IPHex[1]=bcastAddr>>24 & 0x000000ff))
((IPHex[2]=bcastAddr>>16 & 0x000000ff))
((IPHex[3]=bcastAddr>>8 & 0x000000ff))
((IPHex[4]=bcastAddr & 0x000000ff))
echo -e "Broadcast Address : ${IPHex[1]}.${IPHex[2]}.${IPHex[3]}.${IPHex[4]}"
done
|