Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - ip <-> subnet match? [duplicate]

Tags:

python

ip

subnet

Possible Duplicate:
How can I check if an ip is in a network in python

What is the easy way to match subnet to an ip address in python, so that if the ip address is in the subnet I can choose it?

Thanks in advance.

like image 607
0xmtn Avatar asked Mar 15 '12 09:03

0xmtn


People also ask

Can 2 subnets have same IP address?

Generally speaking, no two devices should have the same IP address unless they are behind a NAT device. Computers need routers to communicate with devices that are not on their same logical subnet.

Can IP address duplicate?

In this tech tip, we'll explore how a duplicate IP can happen and what the symptoms are. In most cases, duplicate IP conflicts are due to configuration mistakes. Perhaps a technician added a device to the network with a statically set IP address that is also assigned to the DHCP address pool for that subnet.

How do I remove duplicate IP addresses from my network?

If you defined a static IP address for a network device, duplicate IP address conflicts may occur on a DHCP network. See more details. To resolve it, convert the network device with the static IP address to a DHCP client. Or, you can exclude the static IP address from the DHCP scope on the DHCP server.


2 Answers

In Python 3.3+, you can use ipaddress module:

>>> import ipaddress
>>> ipaddress.ip_address('192.0.43.10') in ipaddress.ip_network('192.0.0.0/16')
True

If your Python installation is older than 3.3, you can use this backport.


If you want to evaluate a lot of IP addresses this way, you'll probably want to calculate the netmask upfront, like

n = ipaddress.ip_network('192.0.0.0/16')
netw = int(n.network_address)
mask = int(n.netmask)

Then, for each address, calculate the binary representation with one of

a = int(ipaddress.ip_address('192.0.43.10'))
a = struct.unpack('!I', socket.inet_pton(socket.AF_INET, '192.0.43.10'))[0]
a = struct.unpack('!I', socket.inet_aton('192.0.43.10'))[0]  # IPv4 only

Finally, you can simply check:

in_network = (a & mask) == netw
like image 189
phihag Avatar answered Sep 23 '22 07:09

phihag


If for a given IP you want to find a prefix from a long list of prefixes, then you can implement longest prefix match. You first build a prefix tree from your list of prefixes, and later, you traverse the tree looking for the furthest leaf that matches your prefix.

It sounds scary, but it is not that bad :)

like image 38
Jakub M. Avatar answered Sep 23 '22 07:09

Jakub M.