IP与数字之间的转化

IP转数字inet_aton()

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)满足使用条件。

# python写法
import socket, struct

def ip_to_long(ip_address):
    """
    convert ip to long
    """
    packed_ip = socket.inet_aton(ip_address)
    # 使用0是因为解包的是一个单元素的元组
    return struct.unpack('!L', packed_ip)[0]

数字转IP函数inet_ntoa()

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)
# python写法
def long_to_ip(long_int):
    """
    convert long to ip
    """
    packed_ip = struct.pack('!L', long_int)
    return socket.inet_ntoa(packed_ip)

你可能感兴趣的:(IP与数字之间的转化)