1
1

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 1 year has passed since last update.

Python で IPv4 アドレスの CIDR 表記を相互変換するやつ

Last updated at Posted at 2023-02-24

Python で IPv4 アドレスの CIDR 表記文字列を数値表現と相互変換する関数を書いた。IPv4 アドレスを数値として扱いたいとき (?) にご活用ください。

def cidr2int(cidr: str) -> tuple[int, int]:
    cidr = cidr.split("/", 1)
    cidr[0] = cidr[0].split(".")
    assert len(cidr[0]) == 4
    addr = 0
    for i, octet in enumerate(cidr[0]):
        assert 0 <= int(octet) <= 0xFF
        addr += int(octet) * 0x100 ** (3 - i)
    prefix = int(cidr[1])
    assert 0 <= prefix <= 32
    mask = 0xFFFFFFFF >> (32 - prefix) << (32 - prefix)
    return addr, mask


def int2cidr(addr: int, mask: int) -> str:
    assert 0 <= addr <= 0xFFFFFFFF
    assert 0 <= mask <= 0xFFFFFFFF
    octets = reversed([(addr & (0xFF * 0x100**i)) >> (i * 8) for i in range(4)])
    return f"{'.'.join([str(octet) for octet in octets])}/{bin(mask).count('1')}"
cidr2int('192.168.1.0/24')  #=> (3232235776, 4294967040)
int2cidr(3232235776, 4294967040)  #=> '192.168.1.0/24'
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?