Created
January 26, 2016 11:22
-
-
Save ceving/09a3f9a4141681f26946 to your computer and use it in GitHub Desktop.
Bash functions for IPv4 network calculations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ip2int() | |
{ | |
local a b c d | |
{ IFS=. read a b c d; } <<< $1 | |
echo $(((((((a << 8) | b) << 8) | c) << 8) | d)) | |
} | |
int2ip() | |
{ | |
local ui32=$1; shift | |
local ip n | |
for n in 1 2 3 4; do | |
ip=$((ui32 & 0xff))${ip:+.}$ip | |
ui32=$((ui32 >> 8)) | |
done | |
echo $ip | |
} | |
netmask() | |
{ | |
local mask=$((0xffffffff << (32 - $1))); shift | |
int2ip $mask | |
} | |
broadcast() | |
{ | |
local addr=$(ip2int $1); shift | |
local mask=$((0xffffffff << (32 -$1))); shift | |
int2ip $((addr | ~mask)) | |
} | |
network() | |
{ | |
local addr=$(ip2int $1); shift | |
local mask=$((0xffffffff << (32 -$1))); shift | |
int2ip $((addr & mask)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment