I've never had a need to do any bit twiddling in bash... thanks for this solution, It was very educational. Brian Cluff On 10/27/2011 11:43 AM, Dale Farnsworth wrote: > 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 > --------------------------------------------------- > PLUG-discuss mailing list - PLUG-discuss@lists.plug.phoenix.az.us > To subscribe, unsubscribe, or to change your mail settings: > http://lists.PLUG.phoenix.az.us/mailman/listinfo/plug-discuss > --------------------------------------------------- PLUG-discuss mailing list - PLUG-discuss@lists.plug.phoenix.az.us To subscribe, unsubscribe, or to change your mail settings: http://lists.PLUG.phoenix.az.us/mailman/listinfo/plug-discuss