tags:

views:

57

answers:

3

I have a lot of IP addresses in a large mysql DB stored as long int's. I need an efficient/quick way to convert them back to an IP within a BASH shell script ( or have mysql return the results as an IP?? ).

Note: specifically don't want to call perl, awk, or other 'language'.

+3  A: 

See the INET_NTOA function, you can use that to convert the number to an IP on the MySQL server.

Lukáš Lalinský
Thanks! Didn't realise you can actually pass the mysql field to INET_NTOA.
Mark
+1  A: 

Suppose you have a field called ip_addr in a table called hosts

Then

select INET_NTOA(ip_addr) from hosts;

Would do the query and return dotted quad IPs in the result set.

Jesse Dhillon
+2  A: 

Since you asked for Bash:

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[*]}"
}

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
}

Examples:

$ INET_ATON 10.2.1.255
167903743
$ INET_NTOA 167903743
10.2.1.255
Dennis Williamson