I have been working on some mocking for IOT devices and I need to generate a random IP address in C#. What is the most simple way to create a random IP address is C#?
If you want to use an IPAddress
object:
var data = new byte[4];
new Random().NextBytes(data);
IPAddress ip = new IPAddress(data);
Note: If you are doing this several times, you should create just one Random
object and reuse it.
If you want to ensure that the first element is not zero, you should OR it with 1 before passing it to the IPAddress constructor:
data[0] |= 1;
...
If you want an IPV6 address, replace the first line with:
var data = new byte[16];
and you'll get an IPV6 address.
Based on using visual studio 2017 and string interpolation
public string GetRandomIpAddress()
{
var random = new Random();
return $"{random.Next(1, 255)}.{random.Next(0, 255)}.{random.Next(0, 255)}.{random.Next(0, 255)}";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With