Re: netmask in a script

Top Page
Attachments:
Message as email
+ (text/plain)
Delete this message
Reply to this message
Author: thomas@redhat.com
Date:  
To: Main PLUG discussion list
Subject: Re: netmask in a script
Have you looked at ipcalc? It does some really cools stuff and can be
scripted.

On 10/27/2011 06:19 PM, Brian Cluff wrote:
> 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 -
>> To subscribe, unsubscribe, or to change your mail settings:
>> http://lists.PLUG.phoenix.az.us/mailman/listinfo/plug-discuss
>>
>
> ---------------------------------------------------
> PLUG-discuss mailing list -
> To subscribe, unsubscribe, or to change your mail settings:
> http://lists.PLUG.phoenix.az.us/mailman/listinfo/plug-discuss



- --
Thomas Cameron, RHCA, RHCSS, RHCDS, RHCVA, RHCX
Chief Architect, Canada and Central US
512-241-0774 office / 512-585-5631 cell
http://people.redhat.com/tcameron/
IRC: choirboy / AIM: rhelguy / Yahoo: rhce_guy /Google+ http://ongpl.us/tdc
---------------------------------------------------
PLUG-discuss mailing list -
To subscribe, unsubscribe, or to change your mail settings:
http://lists.PLUG.phoenix.az.us/mailman/listinfo/plug-discuss