Programming Tutorials

Convert IP address to integer and back to IP address in PHP

By: Darkshire in PHP Tutorials on 2011-04-08  

Here are some tricks to convert from a "dotted" IP address to a LONG int, and backwards. This is very useful because accessing an IP addy in a database table is very much faster if it's stored as a BIGINT rather than in characters.

IP to BIGINT:

<?php
  $ipArr    = explode('.',$_SERVER['REMOTE_ADDR']);
  $ip       = $ipArr[0] * 0x1000000
            + $ipArr[1] * 0x10000
            + $ipArr[2] * 0x100
            + $ipArr[3]
            ;
?>

This can be written in a bit more efficient way:

<?php
  $ipArr    = explode('.',$_SERVER['REMOTE_ADDR']);
  $ip       = $ipArr[0]<<24
            + $ipArr[1]<<16
            + $ipArr[2] <<8
            + $ipArr[3]
            ;
?>
shift is more cheaper.




Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in PHP )

is_utf8 in PHP

Convert IP address to integer and back to IP address in PHP

A Basic Example using PHP in AWS (Amazon Web Services)

Building a Video Sharing Site using PHP in AWS

PHP file upload (Large Files)

Installing PHP with Apache 2.x on HP UX 11i and configuring PHP with Oracle 9i

PHP ./configure RESULTING IN __rcp_thread_destroy@GLIBC_2_2_3_... AND UNRESOLVED REFERENCES WITH ORACLE OCI8

Cannot load /usr/local/apache/libexec/libphp4.so into server: ld.so.1:......

Setting up PHP in Windows 2003 Server IIS7, and WinXP 64

error: "Service Unavailable" after installing PHP to a Windows XP x64 Pro

Running different websites on different versions of PHP in Windows 2003 & IIS6 platform

Installing PHP with nginx-server under windows

Function to force strict boolean values in PHP

Function to sort array by elements and count of element in PHP

Function to convert strings to strict booleans in PHP

Latest Articles (in PHP)