#!/bin/bash

#-------------------------------------------------------------------------------
#   includable functions to convert ipv4 to long integer and back
#   behaves like the mysql funtions with the same name
#   found on http://stackoverflow.com, posted by Dennis Williamson
#
#   Functions:
#     INET_ATON - IP -> integer
#     INET_NTOA - integer -> IP
#-------------------------------------------------------------------------------


#===  FUNCTION  ================================================================
#          NAME:  INET_NTOA
#   DESCRIPTION:  converts IP in long integer format to a string
#    PARAMETERS:  ip as an long integer
#===============================================================================
INET_NTOA() { #{{{
    local IFS=. num quad ip e
    num=$1
    for e in 3 2 1
    do
        (( quad = 256 ** e))
        (( ip[3-e] = num / quad ))
        (( num = num % quad ))
    done
    ip[3]=$num
    echo "${ip[*]}"
} #}}}

#===  FUNCTION  ================================================================
#          NAME:  INET_ATON
#   DESCRIPTION:  converts a IP to a long integer
#    PARAMETERS:  ip as string
#===============================================================================
INET_ATON() { #{{{
    local IFS=. ip num e
    ip=($1)
    for e in 3 2 1
    do
        (( num += ip[3-e] * 256 ** e ))
    done
    (( num += ip[3] ))
    echo $num
} #}}}

