码迷,mamicode.com
首页 > 数据库 > 详细

MySQL中应该怎样存储IP地址

时间:2015-03-13 12:23:18      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

为什么要问如何存储IP

首先就来阐明一下部分人得反问:为什么要问IP得知怎样存,直接varchar类型不久得了吗?

其实做任何程序设计都要在功能实现的基础上最大限度的优化性能。而数据库设计是程序设计中不可忽略的一个重要部分,所以巧存IP地址可以一定程度获得很大提升。

利用函数算法处理

在MySQL中没有直接提供IP类型字段,但如果有两个函数可以把IP与最大长度为10位数字类型互转,所以使用int类型存储IP比varchar类型存储IP地址性能要提升很多,减少不少看空间。因为varchar是可变长形,需要多余的一个字节存储长度。另外int型在逻辑运算上要比varchar速度快。

IP转数字函数inet_aton()

我们转换下几个常用的IP地址

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
mysql> select inet_aton(‘255.255.255.255‘);
+------------------------------+
| inet_aton(‘255.255.255.255‘) |
+------------------------------+
|                   4294967295 |
+------------------------------+
1 row in set (0.00 sec)
 
mysql> select inet_aton(‘192.168.1.1‘);   
+--------------------------+
| inet_aton(‘192.168.1.1‘) |
+--------------------------+
|               3232235777 |
+--------------------------+
1 row in set (0.00 sec)
 
mysql> select inet_aton(‘10.10.10.10‘);
+--------------------------+
| inet_aton(‘10.10.10.10‘) |
+--------------------------+
|                168430090 |
+--------------------------+
1 row in set (0.00 sec)

所以IP的表字段可以设置为INT(10)就好,如果IP获取不到可以直接存0代表获取不到IP的意思

数字转IP函数inet_ntoa()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
mysql> select inet_ntoa(4294967295);
+-----------------------+
| inet_ntoa(4294967295) |
+-----------------------+
| 255.255.255.255       |
+-----------------------+
1 row in set (0.00 sec)
 
mysql> select inet_ntoa(3232235777);
+-----------------------+
| inet_ntoa(3232235777) |
+-----------------------+
| 192.168.1.1           |
+-----------------------+
1 row in set (0.00 sec)
 
mysql> select inet_ntoa(168430090);
+----------------------+
| inet_ntoa(168430090) |
+----------------------+
| 10.10.10.10          |
+----------------------+
1 row in set (0.00 sec)
 
mysql> select inet_ntoa(0);       
+--------------+
| inet_ntoa(0) |
+--------------+
| 0.0.0.0      |
+--------------+
1 row in set (0.00 sec)

注意,0转换为 0.0.0.0

 

from:http://www.qttc.net/201208193.html

MySQL中应该怎样存储IP地址

标签:

原文地址:http://www.cnblogs.com/feiblog/p/4334518.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!