[範例] 計算子網路

看板Python作者 (Duncan)時間12年前 (2011/10/23 22:14), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串1/1
今天寫好的小程式: 輸入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
文章代碼(AID): #1Ef24gnq (Python)