Get IP mask from IP address and mask length in Python

Given the IP address in four-point notation with periods, for example:
192.192.45.1
And the length of the mask, for example, 8, 16, 24, as a rule, but can be any, i.e. 17.

Can someone request code in python to calculate subnet mask? Preferably, I can obtain the result as a 32-bit integer, so that it is easily hashed and then reinterpreted as a dotted square when necessary for printing. I see that python has a socket library, which is basically a wrapper around the unix api socket. I also saw that it has an inet_ntoa () function, but it returns some kind of package structure. I am not very familiar with the Python structure library, so I was hoping someone would have some ideas. Thanks!

+4
source share
2 answers

The easiest way is to use the google ipaddr module. I assume a 25-bit mask below, but as you say it could be anything

>>> import ipaddr >>> mask = ipaddr.IPv4Network('192.192.45.1/25') >>> mask.netmask IPv4Address('255.255.255.128') >>> 

The module is quite effective at manipulating IPv4 and IPv6 addresses ... an example of some other functions in it ...

 >>> ## Subnet number? >>> mask.network IPv4Address('192.192.45.0') >>> >>> ## RFC 1918 space? >>> mask.is_private False >>> >> ## The subnet broadcast address >>> mask.broadcast IPv4Address('192.192.45.127') >>> mask.iterhosts() <generator object iterhosts at 0xb72b3f2c> 
+13
source

You can calculate a 32-bit mask value like this

 (1<<32) - (1<<32>>mask_length) 

eg.

 >>> import socket, struct >>> mask_length = 24 >>> mask = (1<<32) - (1<<32>>mask_length) >>> socket.inet_ntoa(struct.pack(">L", mask)) '255.255.255.0' 
+7
source

Source: https://habr.com/ru/post/1411423/


All Articles