jmnwong
jmnwong

Reputation: 1667

How to determine if IP address in whitelist with IPy?

In Python I am using the IPy module to work with a set of IP addresses such as: - Google's DNS (8.8.8.8) - Some other Google IPs such as 209.85.128.0/17 etc.

myWhiteList = Set(IP('8.8.8.8'), IP('209.85.128.0/17'))

Currently, I take the IP address and subnet mask and create a huge list with all the IPs in the form:

for i in IP('209.85.128.0/17'):
    myList.add(i)

And then check whether my given IP is in this master list. Is there a more efficient way of checking IPs in a list with IPy instead of expanding the IPs like I do here?

Upvotes: 1

Views: 3287

Answers (1)

Excambion
Excambion

Reputation: 70

Something like this:

from IPy import IP
if '192.168.0.1' in IP('192.168.0.0/30'):
    print "My IP is in the whitelist! Yay!"

Or in your case when you have several networks in a list:

for white_net in myWhiteList:
    if my_ip in white_net:
        print "My IP is in the whitelist! Yay!"
        break

Or, you can combine it in a single line:

my_ip = '209.85.128.1'
is_in_whitelist = any([my_ip in white_net for white_net in myWhiteList])

Upvotes: 5

Related Questions