How to convert a CIDR prefix to a dotted-square netmask in Python?
For example, if 12I need to return the prefix 255.240.0.0.
12
255.240.0.0
You can do it as follows:
def cidr(prefix): return socket.inet_ntoa(struct.pack(">I", (0xffffffff << (32 - prefix)) & 0xffffffff))
Here is the lighter side solution (no dependencies between modules):
netmask = '.'.join([str((0xffffffff << (32 - len) >> i) & 0xff) for i in [24, 16, 8, 0]])
:
netmask = 0xFFFFFFFF & (2**(32-len)-1)
, F:
netmask = (2**32-1) & ~ (2 ** (32-len)-1)
( ):
netmask = (1<<32)-1 & ~ ((1 << (32-len))-1)
dotted.quad, inet.ntoa . : 'len' , .
Source: https://habr.com/ru/post/1538487/More articles:Secure web API with form authentication (authorization) and basic authentication (message handler) together - authenticationDjango: block internet connection for testing - pythonPygame Level / Menu Creation - pythonSelect an element from a stream with a uniform distributed probability - algorithmGet ActiveRecord MySQL query result as a hash, not an array - activerecordJavascript line of code in English - javascriptTfs assembly error Unable to register assembly "MyAssembly.dll" - access denied - c ++Individual array sorting using string values - sortingHow to determine if ipton qtconsole is working? - ipythonHow to get a response from negotiator Nancy? - c #All Articles