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

JavaScript must be enabled for certain features to work
* Required information
1000

Comments

No comments yet. Be the first!
(追記) (追記ここまで)
(追記) (追記ここまで)

AltStyle によって変換されたページ (->オリジナル) /