Python 輸入IP地址及掩碼告訴你該網段包含的全部地址(IPy模塊練習)



IPy模塊原本使用時需要輸入正確的網絡位和掩碼,我利用處理報錯的機制實現了輸入任意IP地址和掩碼均可正確輸出結果的小程序。

 

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 # @Date    : 2017-09-04 21:57:15
 4 # @Author  : EnderZhou (zptxwd@gmail.com)
 5 # @Link    : http://www.cnblogs.com/enderzhou/
 6 # @Version : $Id$
 7 
 8 from IPy import IP
 9 
10 def ipip(a):
11     try:
12         ips = IP(a)
13         print a
14         for ip in ips:
15             # print ip 
16             if ip == ips[0]:
17                 print str(ips[0]) + '\t網絡位/The network address'
18             elif ip == ips[1]:
19                 print str(ips[1]) + '\t網關(大多數情況下)/Gateway(in most cases)'#大多數情況下這個英文不知道是否准確^_^!
20             elif ip == ips[-1]:
21                 print str(ips[-1]) + '\t廣播位/Broadcast address'
22             else :
23                 print ip
24     except Exception as e:
25         #利用報錯機制,在報錯時對最后一位數值進行減一操作,利用自我調用嘗試到正確的網絡位實現數據輸出
26         b = (a.split('/')[0]).split('.')
27         a = b[0] + '.' + b[1] + '.' + b[2] + '.' + str(int(b[-1])-1) + '/' + a.split('/')[-1]
28         ipip(a)
29 
30 def main():
31     #執行文件時鍵盤輸入所需要知道的ip地址及掩碼
32     inputip = raw_input('please input IPaddress(example:192.168.1.1/24):\n >>>')
33     ipip(inputip)
34     # ipip('10.10.10.1/30')#測試用例,為了避免重復輸入注釋掉上面兩行,取消本行注釋即可直接運行本程序測試運行情況
35 
36 if __name__ == '__main__':
37     main()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM