Skip to content

Instantly share code, notes, and snippets.

@pyllyukko
Last active September 5, 2024 13:29
Show Gist options
  • Save pyllyukko/5eecd3a7135f74f4b53006d5ddf1c1ea to your computer and use it in GitHub Desktop.
Save pyllyukko/5eecd3a7135f74f4b53006d5ddf1c1ea to your computer and use it in GitHub Desktop.
Convert IP address string to integer
#!/bin/sh
function ip_to_int() {
local -ai M=(16777216 65536 256 1)
local -i INT=0
local OIFS=${IFS}
IFS="."
set -- ${*}
for I in {1..4}
do
let INT+=$[${!I}*${M[I-1]}]
done
IFS=${OIFS}
echo "${INT}"
return 0
}
function int_to_ip() {
local -a IP=($[${1}/16777216] $[${1}%16777216/65536] $[${1}%65536/256] $[${1}%256])
echo "${IP[0]}.${IP[1]}.${IP[2]}.${IP[3]}"
return 0
}
if [[ ${1} =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]
then
ip="${1}"
echo -e "IP address\t\t= ${ip}"
int=$( ip_to_int ${ip} )
echo -e "integer\t\t\t= ${int}"
if hash rax2
then
nbo=$( rax2 -e ${int} )
echo -e "network byte order\t= ${nbo}"
fi
else
echo "IP address?" 1>&2
exit 1
fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment