Convert IP to INT in MYSQL

Discussion in 'MySQL' started by idotcom, Mar 17, 2008.

  1. #1
    Hello,

    I have a geo database that has regular ip address ranges. I would like to convert them to integers to increase performance. Does anyone know how to do that in mysql if the data is already stored in the database? How can I convert the ips to int?

    Any help appreciated.

    Thank you!
     
    idotcom, Mar 17, 2008 IP
  2. AstarothSolutions

    AstarothSolutions Peon

    Messages:
    2,680
    Likes Received:
    77
    Best Answers:
    0
    Trophy Points:
    0
    #2
    The problem is that IPv6 is based on hexidecimal and so whilst you can convert them at the moment to integers by stripping the . it wont work in the future
     
    AstarothSolutions, Mar 17, 2008 IP
  3. kjewat

    kjewat Active Member

    Messages:
    149
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    53
    #3
    kjewat, Mar 17, 2008 IP
  4. idotcom

    idotcom Well-Known Member

    Messages:
    522
    Likes Received:
    15
    Best Answers:
    0
    Trophy Points:
    108
    #4
    I was hoping there was a way to do it with mysql only. So what I ended up doing is running all 2,349,000 records through a loop with php and converting 000.000.000.000 to 000000000 using INET_ATON(). I didn't want to go that route because of the amount of records... I thought it would be really intensive on the server... boy was I wrong :) This successfully changed all 5 million (startip,endip) in like 3 minutes! I was impressed.

    So, if you're storing ip ranges for geoip stuff like maxmind, you may want to store the ips using INET_ATON().

    Then when you're doing a lookup, you do something like this...


    function geoip_encode($ip)
    {
    list( $w, $x, $y, $z ) = explode('.', trim($ip));
    return( (16777216 * $w) + (65536 * $x) + (256 * $y) + $z );
    }

    $ip = geoip_encode($_SERVER['REMOTE_ADDR']);

    SQL: SELECT * FROM GeoTable WHERE $ip BETWEEN startIpNum AND endIpNum

    Thanks guys for your input
     
    idotcom, Mar 17, 2008 IP
  5. ScottR

    ScottR Peon

    Messages:
    1
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    There are functions to covert both ways, e.g.:

    SELECT INET_ATON('192.168.0.10') AS ip_int;

    SELECT INET_NTOA(3232235530) AS ip_str;

    http://dev.mysql.com/doc/refman/5.1/en/miscellaneous-functions.html#function_inet-aton
     
    ScottR, Mar 22, 2010 IP