Heim >Datenbank >MySQL-Tutorial >基于Mysql的IP处理函数inet_aton()与inet_ntoa()的深入分析_MySQL

基于Mysql的IP处理函数inet_aton()与inet_ntoa()的深入分析_MySQL

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-01 13:24:381085Durchsuche

bitsCN.com

有个统计需求,需要对IP进行分类统计,Mysql提供了inet_aton()和inet_ntoa()函数进程处理。
具体可以查看官方手册

INET_ATON(expr)
给出一个作为字符串的网络地址的点地址表示,返回一个代表该地址数值的整数。地址可以是4或8比特地址。

mysql> select inet_ntoa(3507806248);
+-----------------------+
| inet_ntoa(3507806248) |
+-----------------------+
| 209.20.224.40         |
+-----------------------+
1 row in set (0.00 sec)

产生的数字总是按照网络字节顺序。如上面,数字按照 209×2563 + 207×2562 + 224×2561 + 40 ×2560 进行计算。我们来验算下:

mysql> select 209*POW(256,3)+207*POW(256,2)+224*POW(256,1)+40*POW(256,0);
+------------------------------------------------------------+
| 209*POW(256,3)+207*POW(256,2)+224*POW(256,1)+40*POW(256,0) |
+------------------------------------------------------------+
|                                                 3520061480 |
+------------------------------------------------------------+
1 row in set (0.02 sec)

INET_ATON() 也能理解短格式 IP 地址:

mysql> select inet_aton('127.0.0.1'),inet_aton('127.1');
+------------------------+--------------------+
| inet_aton('127.0.0.1') | inet_aton('127.1') |
+------------------------+--------------------+
|             2130706433 |         2130706433 |
+------------------------+--------------------+
1 row in set (0.00 sec)

可以理解成为中间2为地址默认为0。

注: 在存储由INET_ATON() 产生的值时,推荐你使用 INT UNSIGNED 列。假如你使用 (带符号) INT列, 则相应的第一个八位组大于127的IP 地址值会被截至 2147483647 (即, INET_ATON('127.255.255.255′) 所返回的值)。当然,直接使用bigint更加省事。

INET_NTOA(expr)
给定一个数字网络地址 (4 或 8 比特),返回作为字符串的该地址的电地址表示。也就是inet_aton()的反函数。

mysql> select inet_ntoa(3507806248);
+-----------------------+
| inet_ntoa(3507806248) |
+-----------------------+
| 209.20.224.40         |
+-----------------------+
1 row in set (0.00 sec)

bitsCN.com
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn