C# Generating a random IP Address

c#, ip, random

Solution

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.

Problem

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#?

Original source