2

I just want to automatically increase and get IP address which started from any IP range.

For example,

10.1.1.255 (passed value that IP to function)
10.1.2.1 (third octet changed, fourth octet set to '1')

or

10.1.2.11 (passed value that IP to function)
10.1.2.12 (third octet stable, fourth octet increased)

Is is possible to do this like above controlled way?

juniorDev
  • 155
  • 2
  • 13

2 Answers2

3

To offer another possible solution, you could use an Extension method on the System.Net.IPAddress class like so:

public static class MyExtensions
{
    public static System.Net.IPAddress Increment(this System.Net.IPAddress value)
    {
        var ip = BitConverter.ToInt32(value.GetAddressBytes().Reverse().ToArray(), 0);
        ip++;
        return new System.Net.IPAddress(BitConverter.GetBytes(ip).Reverse().ToArray());
    }
}

Then, you would use it like this:

var ipAddress = IPAddress.Parse("10.1.1.255");
var newIpAddress = ipAddress.Increment();
Wyatt Earp
  • 1,783
  • 13
  • 23
1

Try this one:

string[] i = "10.1.1.255".Split('.');

long n = Convert.ToInt64(i[0]) * (long)Math.Pow(256, 3)
        + Convert.ToInt64(i[1]) * (long)Math.Pow(256, 2)
        + Convert.ToInt64(i[2]) * 256
        + Convert.ToInt64(i[3]);

n++;

n = n % (long)Math.Pow(256, 4);

string next = string.Format("{0}.{1}.{2}.{3}", n / (int)Math.Pow(256, 3), (n % (int)Math.Pow(256, 3)) / (int)Math.Pow(256, 2), (n % (int)Math.Pow(256, 2)) / 256, n % 256);

It splits the IP address in pieces. Calculates a numeric value of it. Then it adds one to get the next, check for overflow. Then it outputs the next value.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325