如何在保存到数据库之前将IP地址转换为整数

Rin*_*rge 1 php mysql

我在一些帖子中读过,IP地址可以转换并保存为mysql db中的整数.有人能举例说明吗?

提前致谢.

dee*_*392 6

ip2long()
Run Code Online (Sandbox Code Playgroud)

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

由于您说要将其与MySQL数据库一起使用,因此请使用这两个函数来转换为与MySQL INET_ATON和INET_NTOA兼容的数字.

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

参考MySQL函数:

INET_ATON()     -- Return the numeric value of an IP address
INET_NTOA()     -- Return the IP address from a numeric value
Run Code Online (Sandbox Code Playgroud)

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