Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: "10.0.1.1", "10.0.3.14", "172.23.35.1" and so on.

Could someone give me some help?

like image 346
changzhi Avatar asked Jan 09 '14 07:01

changzhi


2 Answers

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

NOTE This could generate IPs like 0.0.0.0, 255.255.255.255.

like image 82
falsetru Avatar answered Sep 23 '22 01:09

falsetru


If you just want a string:

import random  ip = ".".join(map(str, (random.randint(0, 255)                          for _ in range(4)))) 
like image 28
jonrsharpe Avatar answered Sep 24 '22 01:09

jonrsharpe