[範例] 計算子網路
今天寫好的小程式:
輸入IP位址跟子網路遮罩可以算出屬於哪個網段
我是python新手,寫得落落長,少了註解還請見諒
有甚麼地方改進的,再麻煩指正,謝謝!
#!/usr/bin/env python
import re
def checkIp():
ip_addr=raw_input('Please input a ipaddress: ')
pat_addr=r'(\d*).(\d*).(\d*).(\d*)'
res=re.search(pat_addr,ip_addr).groups()
check=[]
for i in res:
if int(i) > 254:
print i+' you can`t type a byte > 254 it was a wrong addr.'
check.append(0)
else:
check.append(1)
for i in check:
if i == 0:
return 0
else:
return res
def checkSubnetMask():
ip_addr=raw_input('Please input a subnetmask: ')
mask=r'0|128|192|224|240|248|252|255'
pat_addr=r'('+mask+r').('+mask+r').('+mask+r').('+mask+r')'
res=re.search(pat_addr,ip_addr)
if res == None:
print 'You input a wrong mask Number.'
return 0
else:
res=re.search(pat_addr,ip_addr).groups()
return res
def tr_b(res):
x=[]
for i in range(0,4):
x.append(bin(int(res[i])))
return x
def mix_ip_sub(ip,sub):
x=[]
for i in range(0,4):
x.append(str(int(ip[i],2) & int(sub[i],2)))
x='.'.join(x)
return x
while True:
try:
ipaddr=checkIp()
if ipaddr:
while True:
subnetma=checkSubnetMask()
if subnetma:
break
else:
continue
break
except:
print 'please keyin a right format like 192.168.2.250'
print 'The network is: '+mix_ip_sub(tr_b(ipaddr),tr_b(subnetma))
--------------------------------------------------------------------
測試~
Please input a ipaddress: 192.168.2.146
Please input a subnetmask: 255.255.255.0
The network is: 192.168.2.0
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 61.63.126.167
推
10/24 09:42, , 1F
10/24 09:42, 1F