tags:

views:

38

answers:

1

hi all

the following question relevant for ksh script

how to calculate the NETWORK IP according to NETMASK & IP ADDRES

if there are some ready shell script to calculate the NETWORK IP

for example

  NETMASK=255.255.255.0
  IP=172.18.20.10


  then NETWORK IP should be 172.18.20.0

lidia

A: 

Give this a try:

#!/bin/ksh
saveIFS=$IFS
IFS="."
ip=($1)
mask=($2)
for i in {0..3}
do
    (( result[i] = ip[i] & mask[i] ))
done
echo "${result[*]}"
IFS=$saveIFS

Example:

$ ./netip.ksh 172.18.20.10 255.255.255.0
172.18.20.0
Dennis Williamson
Dennis , did you test this script ? , I need be sure that this script was tested , because I need to use it on critical systems
lidia
@lidia: Of course I did, but you should, too. *Caveat emptor* - always. One obvious thing: it does not validate the input. For example, you could enter an IP address or mask with octets greater than 255 or with more or fewer than 4 octets or with non-numeric characters.
Dennis Williamson
Also will work in Bash.
Dennis Williamson

related questions