2012-03-12 80 views
0

我讀過一些文章,IP地址可以轉換並保存爲mysql db中的整數。任何人都可以舉例說明嗎?如何在保存到數據庫之前將IP地址轉換爲整數

在此先感謝。

+0

爲什麼你想將它們轉換爲整數? – JJJ 2012-03-12 10:11:49

+0

整數如何看起來像?只需刪除點或其他轉換? – Sgoettschkes 2012-03-12 10:12:32

+0

INT將下降到只有4個字節的空間比varchar – 2012-03-12 10:12:53

回答

6
ip2long() 

http://php.net/manual/en/function.ip2long.php

既然你說要與一個MySQL數據庫使用,使用這兩個函數從和兼容MySQLs INET_ATON和INET_NTOA數字轉換。

<?php 
    function convertIpToString($ip) 
    { 
     $long = 4294967295 - ($ip - 1); 
     return long2ip(-$long); 
    } 
    function convertIpToLong($ip) 
    { 
     return sprintf("%u", ip2long($ip)); 
    } 
?> 

參考MySQL的功能:

INET_ATON()  -- Return the numeric value of an IP address 
INET_NTOA()  -- Return the IP address from a numeric value 

http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_inet-aton

0

您可以使用ip2long()轉換成int

$Db_ip=ip2long("127.0.0.1"); 

要獲得IP地址

$ip = long2ip($Db_ip); // "127.0.0.1" 
相關問題