Generate Random IP Address in Python

In this tutorial, we are going to learn how to generate a random IP address in Python. First of all, let us know about the IP address.

IP Address basic and format

All the devices connected to a network contains an (Internet Protocol)IP address assigned to it. Most importantly, these systems use internet protocol for communication. To clarify, IP address is an address of the device connected to the internet. As the IP address is similar to the address of a house it is unique for each device. The IP address is of two types:-

  • IPV4
  • IPV6


An IPV4 address is of 32-bits length. It is divided into four parts separated by ‘.’. First 16 bits contain information of the network and the next 8-bits contain the information of Sub-network. Lastly, The last 8- bits contain information of Host.


An IPV6 address is similar to IPV4 but it is of 128-bits length, each part contains 16-bits. It is divided into 8 parts separated by ‘:’. It uses the Hexadecimal number format.

Generating IP address using Faker module in Python:

Further, to generate random IP address in python we need to install a module called a Faker. To install it go to the command prompt in your device and enter the following command.

pip install faker

After that, we should import the Faker class from Faker module in our code. The Faker() class generates both IPV4 and IPV6 addresses. Let’s see an example:-


from faker import Faker
ex = Faker()
ip = ex.ipv4()
ip2 = ex.ipv6()
print('ipv4 address:- ',ip)
print('ipv6 address:- ',ip2)


ipv4 address:-
ipv6 address:- af31:85d7:5f8c:f3a0:5d84:9014:1303:526f

In the above example, we are printing both printing ipv4 and ipv6 addresses simultaneously. The Faker class is assigned to ex variable and we are generating both random ipv4 and ipv6 addresses simultaneously, using ipv4() and ipv6() functions of the Faker class.

Also, read:- How to get IP address of a URL in Python

Leave a Reply

Your email address will not be published. Required fields are marked *