Ollie
Ollie

Reputation: 1170

C# Generating a random IP Address

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

Upvotes: 8

Views: 9633

Answers (2)

Matthew Watson
Matthew Watson

Reputation: 109567

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.

Upvotes: 18

Ollie
Ollie

Reputation: 1170

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)}";
    }

Upvotes: 6

Related Questions