你不應該在PHP內部處理,這就是MySQL本地功能。看到這個例子:
create table iptable (
ip int(32) unsigned not null,
comment varchar(32) not null
);
insert into iptable (ip, comment) values (inet_aton('10.0.0.3'), 'This is 10.0.0.3');
select * from iptable;
+-----------+------------------+
| ip | comment |
+-----------+------------------+
| 167772163 | This is 10.0.0.3 |
+-----------+------------------+
select inet_ntoa(ip) as ip, comment from iptable;
+----------+------------------+
| ip | comment |
+----------+------------------+
| 10.0.0.3 | This is 10.0.0.3 |
+----------+------------------+
如果你想同時處理IPv4和IPv6在同一領域,以及你正在使用MySQL 5.6或更高版本,您可以用VARBINARY(16)和inet6_aton的功能和inet6_ntoa。這就是爲什麼你應該使用MySQL的功能,而不是處理內PHP二進制數據一個更好的例子:
create table iptable2 (
ip varbinary(16) not null,
comment varchar(32) not null
);
insert into iptable2 (ip, comment) values
(inet6_aton('192.168.1.254'), 'This is router 192.168.1.254'),
(inet6_aton('::1'), 'This is ipv6 localhost ::1'),
(inet6_aton('FE80:0000:0000:0000:0202:B3FF:FE1E:8329'), 'This is some large ipv6 example')
;
select * from iptable2;
+------------------+---------------------------------+
| ip | comment |
+------------------+---------------------------------+
| +¿?¦ | This is router 192.168.1.254 |
| ? | This is ipv6 localhost ::1 |
| ¦Ç ??¦ ¦?â) | This is some large ipv6 example |
+------------------+---------------------------------+
select inet6_ntoa(ip) as ip, comment from iptable2;
+--------------------------+---------------------------------+
| ip | comment |
+--------------------------+---------------------------------+
| 192.168.1.254 | This is router 192.168.1.254 |
| ::1 | This is ipv6 localhost ::1 |
| fe80::202:b3ff:fe1e:8329 | This is some large ipv6 example |
+--------------------------+---------------------------------+
你可以看到,通過這樣做,你可以真正避免,以評估在不同格式的IPv6地址,因爲MySQL將它們轉換爲二進制文件並返回到它們最簡單的表達式。
我知道這個問題已經有2年多了,但我想讓這些信息對其他人有用。
HTH
舊金山Zarabozo
忘了補充,我工作在本地主機上,所以也許這就是爲什麼ip2long()不返回任何東西? – blerh 2010-05-02 17:46:34
本地主機的IPv4仍然是127.0.0.1,它應該工作,除非你使用IPv6 - 檢查我的答案。 – 2010-05-02 18:40:15