Python modules you should know: IPy

May 06, 2012 at 04:40 PM | categories: Python, PyMYSK, Howto | View Comments

Next in our series of Python modules you should know is IPy. This package is used to manipulate IPv4 and IPv6 addresses in Python programs.

Home page

Use

The IP class allows a comfortable parsing and handling for most notations in use for IPv4 and IPv6 addresses and networks. It was greatly inspired by RIPE's Perl module NET::IP's interface but doesn't share the implementation.

Installation

pip install IPy

Usage

Print IP addresses in an IP range

from IPy import IP
network = IP('192.168.0.0/30')
for ip in network:
    print ip

Output:

192.168.0.0
192.168.0.1
192.168.0.2
192.168.0.3

Generate Reverse names for reverse lookup/PTR records

from IPy import IP
network = IP('192.168.0.0/30')
for ip in network:
    print ip.reverseName()
from IPy import IP
network = IP('192.168.0.0/30').reverseNames()
for ip in network:
    print ip

Output:

0.0.168.192.in-addr.arpa.
1.0.168.192.in-addr.arpa.
2.0.168.192.in-addr.arpa.
3.0.168.192.in-addr.arpa.

Check IP version:

from IPy import IP
print IP('192.168.0.0/30').version()
print IP('::1').version()

Output:

4
6

Get network prefixes

from IPy import IP
print IP('192.168.0.0/30')
print IP('192.168.0.0/255.255.255.252')
print IP('192.168.0.0-192.168.0.3)

Output:

192.168.0.0/30
192.168.0.0/30
192.168.0.0/30

Get the broadcast address

from IPy import IP
print IP('192.168.0.0/30').broadcast()

Output:

192.168.0.3

Get the network mask

from IPy import IP
print IP('192.168.0.0/30').netmask()

Output:

255.255.255.252

Check if an IP address is within a network

from IPy import IP
'192.168.0.1' in IP('192.168.0.0/30')

Check a network type LOOPBACK, PRIVATE, PUBLIC, RESERVED

from IPy import IP
print IP('192.168.0.1').iptype()

Output:

PRIVATE

And there is more

There is more that can be done using this package please refer to the documentation or run.

import IPy
help(IPy)

blog comments powered by Disqus