Skip to content

Roger Hosto

Good Talk

Menu
  • Home
  • Blogs
    • Databases Administration
      • MySQL
      • NoSQL
    • Development
    • Open Source Software
    • System Administration
  • Resume
  • About
Menu

MySQL Functions for Converting IP Address to an Integer and Back Again

Posted on October 14, 2010 by webgeek

So after my MySQL server-id idea. I was asked to come up with a function to Convert IP Address. So here it is.

use test;
DROP FUNCTION IF EXISTS IpToInteger;
DELIMITER //
CREATE FUNCTION IpToInteger ( ipAddress CHAR(15) )
RETURNS INT UNSIGNED
DETERMINISTIC
BEGIN
DECLARE o1,o2,o3,o4 char(3);
DECLARE IpInteger INT UNSIGNED;
SET o1 = REPLACE(SUBSTRING(SUBSTRING_INDEX( ipAddress, ‘.’, 1), LENGTH(SUBSTRING_INDEX( ipAddress, ‘.’, 1 – 1) ) + 1), ‘.’, ” );
SET o2 = REPLACE(SUBSTRING(SUBSTRING_INDEX( ipAddress, ‘.’, 2), LENGTH(SUBSTRING_INDEX( ipAddress, ‘.’, 2 – 1) ) + 1), ‘.’, ” );
SET o3 = REPLACE(SUBSTRING(SUBSTRING_INDEX( ipAddress, ‘.’, 3), LENGTH(SUBSTRING_INDEX( ipAddress, ‘.’, 3 – 1) ) + 1), ‘.’, ” );
SET o4 = REPLACE(SUBSTRING(SUBSTRING_INDEX( ipAddress, ‘.’, 4), LENGTH(SUBSTRING_INDEX( ipAddress, ‘.’, 4 – 1) ) + 1), ‘.’, ” );
SELECT ( o1 << 24 ) + ( o2 << 16 ) + ( o3 << 8 ) + o4 INTO IpInteger;
RETURN IpInteger;
END//
DELIMITER ;

use test;
DROP FUNCTION IF EXISTS IntegerToIp;
DELIMITER //
CREATE FUNCTION IntegerToIp( ipInteger INT UNSIGNED )
RETURNS CHAR(16) DETERMINISTIC
BEGIN
DECLARE o1,o2,o3,o4 INT UNSIGNED;
SET o1 = ( ipInteger >> 24 );
SET o2 = ( ipInteger >> 16 << 16 )-( ipInteger >> 24 << 24) >> 16;
SET o3 = (ipInteger >> 8 << 8 ) – ( ipInteger >> 16 << 16 ) >> 8;
SET o4 = ipInteger – ( ipInteger >> 8 << 8 );
RETURN CONCAT( o1, “.” , o2, “.” , o3, “.”, o4 );
END//
DELIMITER ;

mysql> SELECT IpToInteger ( '10.8.208.30' ); +-------------------------------+ | IpToInteger ( '10.8.208.30' ) | +-------------------------------+ | 168349726 | +-------------------------------+ 1 row in set (0.00 sec) mysql> SELECT IntegerToIp( 168349726 ); +--------------------------+ | IntegerToIp( 168349726 ) | +--------------------------+ | 10.8.208.30 | +--------------------------+ 1 row in set (0.00 sec) mysql>

 

Category: Databases Administration

Leave a Reply

You must be logged in to post a comment.

  • Back to Basics: ORM and Its Impact on Database and Data Architecture
  • MySQL Error: 1062 'Duplicate entry' Error
  • Installing MariaDB 10.1 on CentOS 6.8
  • Linux Mint
  • Querying Apache Hadoop Resource Manager with Python.
  • LinkedIn
© 2026 Roger Hosto | Powered by Minimalist Blog WordPress Theme