创建表

<pre>

CREATE TABLE `user` (

`id` int(11) unsigned NOT NULL AUTO_INCREMENT,

`name` varchar(100) NOT NULL,

`ip` int(10) unsigned NOT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB;

</pre>

插入几条数据

<pre>

INSERT INTO `user` (`id`, `name`, `ip`) VALUES

(2, 'Abby', inet_aton('192.168.1.1')),

(3, 'Daisy', inet_aton('172.16.11.66')),

(4, 'Christine', inet_aton('220.117.131.12'));

</pre>

查询显示为电地址

<pre>

mysql> select id,name,inet_ntoa(ip) as ip from `user`;

+----+-----------+----------------+

| id | name | ip |

+----+-----------+----------------+

| 2 | Abby | 192.168.1.1 |

| 3 | Daisy | 172.16.11.66 |

| 4 | Christine | 220.117.131.12 |

+----+-----------+----------------+

</pre>

比较方法

如果需要找出在某个网段的用户(例如:172.16.11.1 ~ 172.16.11.100),可以利用PHP的ip2long方法,把ip地址转为整型,再进行比较。

<pre>

mysql> select ip,name,inet_ntoa(ip) as ip from `user` where ip>=2886732545 and ip<=2886732644;

+------------+-------+---------------+

| ip | name | ip |

+------------+-------+---------------+

| 2886732610 | Daisy | 172.16.11.66 |

+------------+-------+---------------+

</pre>

注意:使用ip2long方法把ip地址转为整型时,对于大的ip会出现负数,采取如下方案

<pre>

<?php

$ip = '192.168.101.100';

$ip_long = sprintf('%u',ip2long($ip));

echo $ip_long.PHP_EOL;

?>

</pre>