作者lumpa (Duncan)
看板Python
标题[范例] 计算子网路
时间Sun Oct 23 22:13:59 2011
今天写好的小程式:
输入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
1F:推 freshboy:推新手~ 10/24 09:42