#!/bin/sh belongs_network () { addr=$1 network=$2 netaddr=`echo $network | cut -d / -f 1` netcdr=`echo $network | cut -d / -f 2` a1=$(echo "$addr" | cut -d . -f 1) a2=$(echo "$addr" | cut -d . -f 2) a3=$(echo "$addr" | cut -d . -f 3) a4=$(echo "$addr" | cut -d . -f 4) n1=$(echo "$netaddr" | cut -d . -f 1) n2=$(echo "$netaddr" | cut -d . -f 2) n3=$(echo "$netaddr" | cut -d . -f 3) n4=$(echo "$netaddr" | cut -d . -f 4) ares=$((($a1*256*256*256+$a2*256*256+$a3*256+$a4)>>(32-$netcdr))) nres=$((($n1*256*256*256+$n2*256*256+$n3*256+$n4)>>(32-$netcdr))) if [ $ares -eq $nres ] ; then return 0 else return 1 fi } if belongs_network 10.208.103.255 10.208.128.0/17; then echo "belongs" else echo "does not belong" fi
пятница, 13 октября 2017 г.
Does ip belong to network?
It's so easy to check if IP belong to network... Until you start doing this in shell. I've tried and finally got this. This version works in bash, dash and ksh...
Good enough for me, but perhaps it could be optimized a bit to avoid cut usage.
Our function gets two parameters - ip address and network in address/netmask format. In fact we compare IPaddress & netmask and IPnetwork & netmask.
Подписаться на:
Сообщения (Atom)