Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Generating a random IP Address

Tags:

c#

random

ip

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

like image 832
Ollie Avatar asked May 04 '17 08:05

Ollie


2 Answers

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.

like image 84
Matthew Watson Avatar answered Sep 25 '22 23:09

Matthew Watson


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)}";
    }
like image 26
Ollie Avatar answered Sep 23 '22 23:09

Ollie