How to Manipulate IP Addresses in Python using ipaddress Module?
Last Updated :
21 Sep, 2021
IP Address stands for internet protocol address. It's an identifying number that's related to a selected computer or network. When connected to the web, the IP address allows the computers to send and receive information. Python provides ipaddress module which provides the capabilities to create, manipulate and operate on IPv4 and IPv6 addresses and networks. This module comes inbuilt with python 3.3+, so you don't need to install it if you have python 3.3+. Although you can install it using pip.
pip install ipaddress
The module has IPv4Address class and IPv6Address class to handle IPv4 and IPv6 formats respectively. Since IPv4Address and IPv6Address objects share a lot of common attributes we will see for IPv4 format only and similarly we can do for IPv6 format.
IPv4Address
The IPv4Address objects have a lot of attributes for IPv4 address. ipaddress.IPv4Address('address') construct an IPv4Address object representing IPv4 address 'address'. Some attributes of the class are as follows:
- max_prefixlen: Return the total number of bits in the IP address represented by IPv4Address object (32 for IPv4 and 128 for IPv6).
- is_multicast: Return True if the address is reserved for multicast use.
- is_private: Return True if the address is allocated for private networks.
- is_global: Return True if the address is allocated for public networks.
- is_unspecified: Return True if the address is unspecified.
- is_reserved: Return True if the address is otherwise IETF reserved.
- is_loopback: Return True if this is a loopback address.
- is_link_local: Return True if the address is reserved for link-local usage.
We can also use comparison operators to compare address objects. Also, we can add or subtract integers from the address object.
Now let's see an example of these attributes.
Example:
Python3
import ipaddress
# Creating an object of IPv4Address class and
# initializing it with an IPv4 address.
ip = ipaddress.IPv4Address('112.79.234.30')
# Print total number of bits in the ip.
print("Total no of bits in the ip:", ip.max_prefixlen)
# Print True if the IP address is reserved for multicast use.
print("Is multicast:", ip.is_multicast)
# Print True if the IP address is allocated for private networks.
print("Is private:", ip.is_private)
# Print True if the IP address is global.
print("Is global:", ip.is_global)
# Print True if the IP address is unspecified.
print("Is unspecified:", ip.is_unspecified)
# Print True if the IP address is otherwise IETF reserved.
print("Is reversed:", ip.is_reserved)
# Print True if the IP address is a loopback address.
print("Is loopback:", ip.is_loopback)
# Print True if the IP address is Link-local
print("Is link-local:", ip.is_link_local)
# next ip address
ip1 = ip + 1
print("Next ip:", ip1)
# previous ip address
ip2 = ip - 1
print("Previous ip:", ip2)
# Print True if ip1 is greater than ip2
print("Is ip1 is greater than ip2:", ip1 > ip2)
Output:
Total no of bits in the ip: 32
Is multicast: False
Is private: False
Is global: True
Is unspecified: False
Is reversed: False
Is loopback: False
Is link-local: False
Next ip: 112.79.234.31
Previous ip: 112.79.234.29
Is ip1 is greater than ip2: True
IPv4Network
IPv4Network objects are used to inspect and define IP networks. All the attributes for address object are also valid for network object, additionally, network object provides additional attributes. Some of them is listed below.
- network_address: Return the network address for the network.
- broadcast_address: Return the broadcast address for the network. Packets sent to the broadcast address should be received by every host on the network.
- netmask: Return network mask of the network.
- with_netmask: Return a string representation of the network, with the mask in netmask notation.
- with_hostmask: Return a string representation of the network, with the mask in host mask notation.
- prefixlen: Return the length of the network prefix in bits.
- num_addresses: Return the total number of the address of this network.
- hosts(): Returns an iterator over the usable hosts in the network. The usable hosts are all the IP addresses that belong to the network, except the network address itself and the network broadcast address.
- overlaps(other): Return True if this network is partly or wholly contained in other or other is wholly contained in this network.
- subnets(prefixlen_diff): Return the subnets that join to make the current network definition, depending on the argument values. The prefixlen_diff parameter is the integer that indicates the amount our prefix length should be increased by.
- supernet(prefixlen_diff): Return the supernet containing this network definition, the prefixlen_diff is the amount our prefix length should be decreased by.
- subnet_of(other): Return True if this network is a subnet of other (new in python 3.7).
- supernet_of(other): Return True if this network is a supernet of other (new in python 3.7).
- compare_networks(other): Compare ip network with the other IP network. In this comparison only the network addresses are considered, host bits aren’t. It returns either -1, 0, or 1.
Now let's see an example of the above methods.
Example:Â
Python3
import ipaddress
# Initializing an IPv4 Network.
network = ipaddress.IPv4Network("192.168.1.0/24")
# Print the network address of the network.
print("Network address of the network:", network.network_address)
# Print the broadcast address
print("Broadcast address:", network.broadcast_address)
# Print the network mask.
print("Network mask:", network.netmask)
# Print with_netmask.
print("with netmask:", network.with_netmask)
# Print with_hostmask.
print("with_hostmask:", network.with_hostmask)
# Print Length of network prefix in bits.
print("Length of network prefix in bits:", network.prefixlen)
# Print the number of hosts under the network.
print("Total number of hosts under the network:", network.num_addresses)
# Print if this network is under (or overlaps) 192.168.0.0/16
print("Overlaps 192.168.0.0/16:", network.overlaps(ipaddress.IPv4Network("192.168.0.0/16")))
# Print the supernet of this network
print("Supernet:", network.supernet(prefixlen_diff=1))
# Print if the network is subnet of 192.168.0.0/16.
print("The network is subnet of 192.168.0.0/16:",
network.subnet_of(ipaddress.IPv4Network("192.168.0.0/16")))
# Print if the network is supernet of 192.168.0.0/16.
print("The network is supernet of 192.168.0.0/16:",
network.supernet_of(ipaddress.IPv4Network("192.168.0.0/16")))
# Compare the ip network with 192.168.0.0/16.
print("Compare the network with 192.168.0.0/16:",
network.compare_networks(ipaddress.IPv4Network("192.168.0.0/16")))
Output:
Network address of the network: 192.168.1.0
Broadcast address: 192.168.1.255
Network mask: 255.255.255.0
with netmask: 192.168.1.0/255.255.255.0
with_hostmask: 192.168.1.0/0.0.0.255
Length of network prefix in bits: 24
Total number of hosts under the network: 256
Overlaps 192.168.0.0/16: True
Supernet: 192.168.0.0/23
The network is subnet of 192.168.0.0/16: True
The network is supernet of 192.168.0.0/16: False
Compare the network with 192.168.0.0/16: 1
Â
Similar Reads
How to determine the user IP address using node.js ? Node.js is an open-source, back-end JavaScript runtime environment that runs on the web engine and executes JavaScript code. There are various platforms such as Windows, Linux, Mac OS Â where Node.js can run. The Domain Name System is a hierarchical and decentralized naming system for computers etc t
2 min read
Create a GUI to find the IP for Domain names using Python Prerequisite: Python GUI â tkinterIn this article, we are going to see how to find IP from Domain Names and bind it with GUI Application using Python. We will use iplookup module for looking up IP from Domain Names. It is a small module which accepts a single domain as a string, or multiple domains
2 min read
How to get IP Address of clients machine in PHP ? An IP address is used to provide an identity to a device connected to a network. IP address stands for Internet Protocol address. An IP address allows to track the activities of a user on a website and also allows the location of different devices that are connected to the network to be pinpointed a
2 min read
Working with IP Addresses in Python IP (Internet Protocol) -Address is the basic fundamental concept of computer networks which provides the address assigning capabilities to a network. Python provides ipaddress module which is used to validate and categorize the IP address according to their types(IPv4 or IPv6). This module is also u
3 min read
Telnet with ipaddress and port in Python Telnet is a protocol that allows you to connect to a remote computer and execute commands. Python provides a built-in module called "telnetlib" that enables us to use Telnet in our code. What is Telnet in Python?Telnet clients let you connect to other Telnet Servers. You cannot connect to your own s
3 min read
How to get client IP address using JavaScript? Imagine your computer as your apartment. Just like each apartment has a unique address for receiving mail, your computer has an IP address that helps it receive information from the internet. This IP address acts like a label that identifies your specific device on the vast network of computers, ens
2 min read
Extract IP address from file using Python Let us see how to extract IP addresses from a file using Python. Algorithm :  Import the re module for regular expression.Open the file using the open() function.Read all the lines in the file and store them in a list.Declare the pattern for IP addresses. The regex pattern is :  r'(\d{1,3}\.\d{1,3
2 min read
How to get value from address in Python ? In this article, we will discuss how to get the value from the address in Python. First, we have to calculate the memory address of the variable or python object which can be done by using the id() function. Syntax: id(python_object) where, python_object is any python variable or data structure like
4 min read
Extracting MAC address using Python MAC address also known as physical address is the unique identifier that is assigned to the NIC (Network Interface Card) of the computer. NIC helps in connection of a computer with other computers in the network. MAC address is unique for all the NIC's. Uses of MAC address : Useful in places where I
3 min read
How to Make a DNS Spoof attack using Scapy in Python? In this article, we are going to discuss how to make a DNS Spoof attack using Scapy in Python. Before starting we need to know few points: DNS Server: The Domain Name System provides a way to match human-readable domain names into IP addresses. Â For example, when we search for google.com, the browse
5 min read