netmask in a script

Dale Farnsworth dale at farnsworth.org
Thu Oct 27 11:43:30 MST 2011


Larry wrote:
> I would like to apply a netmask to an arbitrary IP in a bash/dash script
> (e.g. apply 255.255.255.0 to 173.10.3.155 to get 173.10.3.0).  Is there any
> easy way to do that without taking the IP apart, doing 4 operations and
> reassembling the results?

I know you said without disassembly/reassembly, but here are some
bash functions that apply the mask using disassembly/reassembly.

===================== begin =======================
to_int()
{
	# Convert from dotted-quad to integer
	local i=$1
	local OIFS="$IFS"
	IFS=.
	i=($i)
	IFS="$OIFS"
	echo $(((${i[0]} << 24) + (${i[1]} << 16) + (${i[2]} << 8) + ${i[3]}))
}

to_ip()
{
	# Covert from integer to dotted-quad
	local d=$1
	echo $(($d >> 24)).$(($d >> 16 & 255)).$(($d >> 8 & 255)).$(($d&255))
}

and_ip()
{
	# And two ip addresses in dotted-quad format
	local ip1=$1
	local ip2=$2
	echo $(to_ip $(($(to_int $ip1) & $(to_int $ip2))))
}
===================== end =======================

Just pass the ip and netmask to and_ip:
Example:

$ and_ip 11.22.33.44 255.255.255.0
11.22.33.0

-Dale


More information about the PLUG-discuss mailing list