請編寫一個函數實現將IP地址轉換成一個整數。(3分)
如
10.3.9.12
轉換規則為:
10 00001010
3 00000011
9 00001001
12 00001100
再將以上二進制拼接起來計算十進制結果:00001010 00000011 00001001 00001100 = ?
#用Python獲取本機ip地址
from socket import gethostbyname_ex, gethostname
local_IP_list = gethostbyname_ex(gethostname())
local_IP = gethostbyname_ex(gethostname())[2][2]
print(local_IP_list)
print(local_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 = s.join(l)
return s
ipfunc(local_IP)
如

轉換規則為:
10 00001010
3 00000011
9 00001001
12 00001100
再將以上二進制拼接起來計算十進制結果:00001010 00000011 00001001 00001100 = ?
#用Python獲取本機ip地址
from socket import gethostbyname_ex, gethostname
local_IP_list = gethostbyname_ex(gethostname())
local_IP = gethostbyname_ex(gethostname())[2][2]
print(local_IP_list)
print(local_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 = s.join(l)
return s
ipfunc(local_IP)