有時候我們用數據庫存儲ip地址時可以將ip地址轉換成整數存儲,整數占用空間小,索引也會比較方便。
請編寫一個函數實現將IP地址轉換成一個整數。
如 10.3.9.12 ,轉換規則為:
10 00001010
3 00000011
9 00001001
12 00001100
二進制拼接起來計算十進制結果:00001010 00000011 00001001 00001100 = ?
此題利用int() 函數即可解決。int() 函數用於將一個字符串或數字轉換為整型。
# 不傳入參數時,得到結果0 int() # 0 int(3) # 3 int(3.6) # 3 # 如果是帶參數base的話,為進制。並且,數據要以字符串的形式進行輸入。 int('12',16) # 18 int('0xa',16) # 10 int('10',8) # 8
將二進制數轉換為整數,並且連為IP。
def text(b): list_str=b.split(" ") new_str=[] for i in list_str: new_str.append(str(int(i,2))) return ".".join(new_str) print(text("00001010 00000011 00001001 00001100")) # 10.3.9.12
將IP轉換為二進制
def ipfunc(ip): a = ip.split('.') s = '' l = [] for i in a: i = bin(int(i))[2:] i = i.rjust(8, '0') l.append(i) s = ' '.join(l) return s print(ipfunc('10.3.9.12'))
ip轉換成整數的函數
import socket, struct def ip_to_long(ip): """ Convert an IP string to long """ packedIP = socket.inet_aton(ip) return struct.unpack("!L", packedIP)[0] print(ip_to_long('127.0.0.1')) # 2130706433
整數轉換成ip地址
import socket, struct def long_to_ip(long): """ Convert an long string to IP """ return socket.inet_ntoa(struct.pack('!L',long )) # 注意傳參時,不要加引號 print(long_to_ip(2130706433)) # 127.0.0.1
利用Python獲取本機IP
from socket import gethostbyname_ex, gethostname local_IP_list = gethostbyname_ex(gethostname()) local_IP = gethostbyname_ex(gethostname())[2] print(local_IP_list) print(local_IP)
https://blog.csdn.net/bangqin0414/article/details/101890700
