2012-03-12 103 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"