LoginSignup
4
5

More than 5 years have passed since last update.

PythonでCIDR表記を変換

Posted at

Python だと netaddr というモジュールを使えばできそうですが、
CIDR変換だけが必要だったので自分で書いてみました。

>>> import socket, struct
>>> def cidr2mask(len):
...     return socket.inet_ntoa(struct.pack('!L', 0xffffffff ^ ((1 << 32-len)-1)))
... 
>>> cidr2mask(8)
'255.0.0.0'
>>> cidr2mask(16)
'255.255.0.0'
>>> cidr2mask(24)
'255.255.255.0'
>>> cidr2mask(20)
'255.255.240.0'

もっとエレガントな書き方がありそう。

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5