0
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PythonでCIDR表記のネットマスクをドット付き十進表記に変換

Posted at

ネットマスクをドット付き十進表記 (A.B.C.D) から CIDR 表記へ変換する方法は以前に投稿したのですが、その逆に変換する必要に迫られたので書いてみました。

なおエラー処理はしていませんので、おかしなネットマスクを渡すとおかしな値が帰ってきます。ご注意ください。

コード

import socket
import struct

def mask2cidr(mask):
    """Convert netmask from Dotted address to CIDR."""
    return bin(struct.unpack('!L', socket.inet_pton(socket.AF_INET, mask))[0])[2:].index('0')

テスト

>>> mask2cidr('255.255.255.0')
24
>>> mask2cidr('255.255.240.0')
20
>>> mask2cidr('255.255.255.192')
26

参考

0
4
6

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
0
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?