2017年10月9日 星期一

[ Python 常見問題 ] How do you determine if an IP address is private, in Python?

Source From Here 
Question 
In Python, what is the best way to determine if an IP address (e.g., '127.0.0.1' or '10.98.76.6') is on a private network? The code does not sound difficult to write. But there may be more edge cases than are immediately apparent, and there's IPv6 support to consider, etc. Is there an existing library that does it? 

How-To 
Check out the IPy module. If has a function iptype() that seems to do what you want: 
>>> from IPy import IP 
>>> ip = IP('127.0.0.0/30') 
>>> dir(ip) // Check what IPs being supported 
... 
>>> ip.version() 
4 // IPv4 
>>> ip.iptype() 
'PRIVATE' 
>>> ip.net() 
IP('127.0.0.0') 
>>> ip.netmask() 
IP('255.255.255.252') 
>>> ip2 = IP('35.184.152.62') 
>>> ip2.iptype() 
'PUBLIC'


沒有留言:

張貼留言

[ Py DS ] Ch1 - IPython: Beyond Normal Python

Source From  Here   Keyboard Shortcuts in the IPython Shell   If you spend any amount of time on the computer, you’ve probably found a u...