Python randomly generated IP address as string


In Python, what should I do if I want to generate a random string in the form of an IP address?

For example: "", "", "" and so on.

Could someone give me some help?

Asked By: changzhi



>>> import random
>>> import socket
>>> import struct
>>> socket.inet_ntoa(struct.pack('>I', random.randint(1, 0xffffffff)))
>>> socket.inet_ntoa(struct.pack('>I', random.randint(1, 0xffffffff)))

NOTE This could generate IPs like,

Answered By: falsetru

If you just want a string:

import random

ip = ".".join(map(str, (random.randint(0, 255) 
                        for _ in range(4))))
Answered By: jonrsharpe
In [123]: '.'.join('%s'%random.randint(0, 255) for i in range(4))
Out[123]: ''

In [124]: '.'.join('%s'%random.randint(0, 255) for i in range(4))
Out[124]: ''
Answered By: zhangxaochen

It may be too obvious but if you need random IPs within a range you can use this:

import random

for x in xrange(1,100):
  ip = "192.168."
  ip += ".".join(map(str, (random.randint(0, 255) 
                          for _ in range(2))))

  print ip
Answered By: Halil Kaskavalci

import faker
fake = Factory.create()
ip_addr = fake.ipv4(network=False)

lib has a lot of other useful options to fake data.

Answered By: DmitrySemenov
from faker import Faker  
faker = Faker()  
ip_addr = faker.ipv4()  

Reference: Fake-Apache-Log-Generator

Answered By: Sandeep Kanabar

An alternative way to generate a random string in the form of an IP address is:

>>> ip = '{}.{}.{}.{}'.format(*__import__('random').sample(range(0,255),4))
>>> ip
Answered By: coder

You also have Python’s ipaddress module available to you, useful more broadly for creating, manipulating and operating on IPv4 and IPv6 addresses and networks:

import ipaddress
import random

MAX_IPV4 = ipaddress.IPv4Address._ALL_ONES  # 2 ** 32 - 1
MAX_IPV6 = ipaddress.IPv6Address._ALL_ONES  # 2 ** 128 - 1

def random_ipv4():
    return  ipaddress.IPv4Address._string_from_ip_int(
        random.randint(0, MAX_IPV4)

def random_ipv6():
    return ipaddress.IPv6Address._string_from_ip_int(
        random.randint(0, MAX_IPV6)


>>> random.seed(444)                                                                                                                                                                                                                                         
>>> random_ipv4()                                                                                                                                                                                                                                            
>>> random_ipv4()                                                                                                                                                                                                                                            
>>> random_ipv4()                                                                                                                                                                                                                                            
>>> random_ipv6()                                                                                                                                                                                                                                            
>>> random_ipv6()                                                                                                                                                                                                                                            
>>> random_ipv6()                                                                                                                                                                                                                                            
Answered By: Brad Solomon

Faster: Mimesis

If you’re looking for speed, try out Mimesis

from mimesis import Internet 
random_ip = Internet().ip_v4()

enter image description here

IP with valid CIDR: Faker

If you’re looking to generate a random IP adress with a valid CIDR, try out Faker

from faker import Faker  
random_valid_ip = Faker().ipv4()  

enter image description here

For more details on why Faker takes longer, see this issue.

Answered By: Miguel Trejo
from faker import Factory

fake_generator = Factory.create()

Be sure to pip install prior to trying to run the above!

pip install Faker

Check out the package documentation:

Here is a link directly to the ipv4 method docs

Answered By: Copy and Paste

If trying to only generate private IP addresses based off user space (,, and

This post gives good answers

If you are trying to generate ANYTHING else, which can be considered public, use this (my code is based off the post above):

import random
def randomPublicIPaddress():
    oct 1 - cant be 10
    oct 2 - if oct1 == 192
                cant be 168
            if oct1 == 172
                cant be 16-31
    oct 3 - can be anything
    oct 4 - can be anything
    oct1 = random.choice([i for i in range(0,255) if i not in [10,127]])
    if oct1 == 192:
        oct2 = random.choice([i for i in range(0,255) if i not in [168]])
    elif oct1 == 172:
        oct2 = random.choice([i for i in range(0,255) if i not in range(16,31)])
        oct2 = random.randint(0,255)
    oct3 = random.randint(0,255)
    oct4 = random.randint(0,255)

    return ".".join(map(str,([oct1,oct2,oct3,oct4])))

Word of warning, there are many other ip address ranges that are considered "private" make sure to review the list on IANA

Answered By: Dave
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.