1
2

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 ipaddressパッケージ メモ

Last updated at Posted at 2014-09-30

ipaddressパッケージ

http://docs.python.jp/3/library/ipaddress.html
Python3.3で追加。
Backportあり。

remote_hostが「IPv4アドレス」「IPv6アドレス」「その他」のどれであるかを判別する。

ipaddress.ip_address()は、入力値がunicode型でなければエラーとなるので注意。

import ipaddress

def type_of_remote_host(remote_host):
    try:
        addr = ipaddress.ip_address(unicode(address))
        if addr.version == 4:
            return 'ipv4addr'
        else:
            return 'ipv6addr'

    except ValueError:
        return 'other'

IPv6アドレスの冗長形、短縮形の相互変換

import ipaddress

ipaddress.ip_address(u'2001:0db8:0000:0000:0000:0000:0000:9abc').compressed
# => u'2001:db8::9abc'

ipaddress.ip_address(u'2001:db8::9abc').exploded
# => '2001:0db8:0000:0000:0000:0000:0000:9abc'

IPアドレスから逆引き用ホスト名を取得

import ipaddress

## IPv4
'.'.join(reversed('192.168.0.1'.split('.')))+'.in-addr.arpa.'
# => '1.0.168.192.in-addr.arpa.'

## IPv6
'.'.join(reversed(ipaddress.ip_address(u'2001:db8::9abc').exploded.replace(':','')))+'.ip6.arpa.'
# => 'c.b.a.9.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa.'

1
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?