Python randomly generated IP address as string

前端 未结 9 2077
遥遥无期
遥遥无期 2020-12-29 23:14

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

For example: \"10.0.1.1\", \"10.0.3.14\",

相关标签:
9条回答
  • 2020-12-29 23:56

    Faster: Mimesis

    If you're looking for speed, try out Mimesis

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

    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()  
    

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

    0 讨论(0)
  • 2020-12-29 23:59

    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
    '45.162.105.102'
    
    0 讨论(0)
  • 2020-12-30 00:01

    If you just want a string:

    import random
    
    ip = ".".join(map(str, (random.randint(0, 255) 
                            for _ in range(4))))
    
    0 讨论(0)
提交回复
热议问题