简体   繁体   中英

How can I increment an IP address by a specified amount?

I am trying to figure out how to increment a starting ip address, and increment it by an offset that I specify. I have attempted to do this, but I am doing something wrong because I am getting IPs that are all over the place, not even in the same network range.

What I am currently doing is taking my starting ip and ending ip, getting the total amount of addresses then incrementing the total ips by an offset then attempting to actually increment the IP.

I am incrementing to the total ips by an offset so I know how many to increment the ip. (I am completing different tasks per offset.) Whatever the loop has incremented "t" to that is how many I increment IPs. Now that I have given the rundown, my issue only seems to be with actually incrementing ips, can anyone help me out in this situation. Thanks.

            string from = txtStart.Text, to = txtEnd.Text;
            uint current = from.ToUInt(), last = to.ToUInt();

            ulong total = last - current;
            int offset = 3; //This is an example number, it actually could be anything.

            while (current <= last)
            {
             for (int t = 0; t < total; t += offset)
                    {
                        uint ut = Convert.ToUInt32(t);
                        current = current + ut;
                        var ip = current.ToIPAddress();
                    }  
              }

Here is the extension class I am using. They work fine.

public static class Extensions
    {
        public static uint ToUInt(this string ipAddress)
        {
            var ip = IPAddress.Parse(ipAddress);
            var bytes = ip.GetAddressBytes();
            Array.Reverse(bytes);
            return BitConverter.ToUInt32(bytes, 0);
        }

        public static string ToString(this uint ipInt)
        {
            return ToIPAddress(ipInt).ToString();
        }

        public static IPAddress ToIPAddress(this uint ipInt)
        {
            var bytes = BitConverter.GetBytes(ipInt);
            Array.Reverse(bytes);
            return new IPAddress(bytes);
        }
    }
[TestFixture]
public class GetNextIpAddressTest
{
    [Test]
    public void ShouldGetNextIp()
    {
        Assert.AreEqual("0.0.0.1", GetNextIpAddress("0.0.0.0", 1));
        Assert.AreEqual("0.0.1.0", GetNextIpAddress("0.0.0.255", 1));
        Assert.AreEqual("0.0.0.11", GetNextIpAddress("0.0.0.1", 10));
        Assert.AreEqual("123.14.1.101", GetNextIpAddress("123.14.1.100", 1));
        Assert.AreEqual("0.0.0.0", GetNextIpAddress("255.255.255.255", 1));
    }

    private static string GetNextIpAddress(string ipAddress, uint increment)
    {
        byte[] addressBytes = IPAddress.Parse(ipAddress).GetAddressBytes().Reverse().ToArray();
        uint ipAsUint = BitConverter.ToUInt32(addressBytes, 0);
        var nextAddress = BitConverter.GetBytes(ipAsUint + increment);
        return String.Join(".", nextAddress.Reverse());
    }
}

An IPv4 address is basically a 32 bit Integer. Therefore you can just parse the substrings from eg 192.168.0.1 and convert each byte to an integer number:

uint byte1 = Converter.ToUint32("192");

and so on ..

Then you could just "OR" or "ADD" them together like this:

uint IP = (byte1 << 24) | (byte2 << 16) | (byte3 << 8) | byte4;

and increment that integer with step_size as needed. Here is an example:

using System.IO;
using System;

class Program
{
    static void Main()
    {

        String ipString = "192.168.0.1";

        String[] ipBytes = ipString.Split('.');

        uint byte1 = Convert.ToUInt32(ipBytes[0]);
        uint byte2 = Convert.ToUInt32(ipBytes[1]);
        uint byte3 = Convert.ToUInt32(ipBytes[2]);
        uint byte4 = Convert.ToUInt32(ipBytes[3]);

        uint IP =   (byte1 << 24) 
                  | (byte2 << 16) 
                  | (byte3 <<  8) 
                  |  byte4 ;

        uint step_size = 90000000;

        while( IP != 0xFFFFFFFF ) {

            Console.WriteLine(
                  ((IP >> 24) & 0xFF) + "." +
                  ((IP >> 16) & 0xFF) + "." +
                  ((IP >> 8 ) & 0xFF) + "." +
                  ( IP        & 0xFF)
                );

             // if (0xFFFFFFFF - IP) < step_size then we can't 
             // add step_size to IP due to integer overlow
             // which means that we have generated all IPs and 
             // there isn't any left that equals IP + step_size
             if( (0xFFFFFFFF - IP) < step_size ) {
                 break;
             }

             IP += step_size; // next ip address
        }
    }
}

Output

192.168.0.1
198.5.74.129
203.98.149.1
208.191.223.129
214.29.42.1
219.122.116.129
224.215.191.1
230.53.9.129
235.146.84.1
240.239.158.129
246.76.233.1
251.170.51.129

The following is a class I use for working with IP addresses which includes the ability to increment an IP address as well as to build a range of IPs.

public sealed class IPAddressTools
{
    public static UInt32 ConvertIPv4AddressToUInt32(IPAddress address)
    {
        if (address == null) throw new ArgumentNullException("address", "The value of address is a null reference.");
        if (address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork) throw new ArgumentException("The specified address's family is invalid.", "address");

        Byte[] addressBytes = address.GetAddressBytes();
        UInt32 addressInteger = (((UInt32)addressBytes[0]) << 24) + (((UInt32)addressBytes[1]) << 16) + (((UInt32)addressBytes[2]) << 8) + ((UInt32)addressBytes[3]);
        return addressInteger;
    }
    public static IPAddress ConvertUInt32ToIPv4Address(UInt32 addressInteger)
    {
        if (addressInteger < 0 || addressInteger > 4294967295) throw new ArgumentOutOfRangeException("addressInteger", "The value of addressInteger must be between 0 and 4294967295.");

        Byte[] addressBytes = new Byte[4];
        addressBytes[0] = (Byte)((addressInteger >> 24) & 0xFF);
        addressBytes[1] = (Byte)((addressInteger >> 16) & 0xFF);
        addressBytes[2] = (Byte)((addressInteger >> 8) & 0xFF);
        addressBytes[3] = (Byte)(addressInteger & 0xFF);
        return new IPAddress(addressBytes);
    }
    public static IPAddress IncrementIPAddress(IPAddress address, int offset)
    {
        return ModIPAddress(address, 1);
    }
    public static IPAddress ModIPAddress(IPAddress address, int offset)
    {
        if (address == null) throw new ArgumentNullException("address", "The value of address is a null reference.");
        if (address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork) throw new ArgumentException("The specified address's family is invalid.");

        UInt32 addressInteger = ConvertIPv4AddressToUInt32(address);
        addressInteger += offset;
        return ConvertUInt32ToIPv4Address(addressInteger);
    }
    public static IPAddress[] GetIpRange(IPAddress address, IPAddress mask)
    {
        if (address == null) throw new ArgumentNullException("address", "The value of address is a null reference.");
        if (mask == null) throw new ArgumentNullException("mask", "The value of mask is a null reference.");
        if (address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork) throw new ArgumentException("The specified address's family is invalid.");
        if (mask.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork) throw new ArgumentException("The specified mask's family is invalid.");

        byte[] addressBytes = address.GetAddressBytes();
        byte[] maskBytes = mask.GetAddressBytes();
        byte[] startIpBytes = new byte[addressBytes.Length];
        byte[] endIpBytes = new byte[addressBytes.Length];

        for (int i = 0; i < addressBytes.Length; i++)
        {
            startIpBytes[i] = (byte)(addressBytes[i] & maskBytes[i]);
            endIpBytes[i] = (byte)(addressBytes[i] | ~maskBytes[i]);
        }

        IPAddress startIp = new IPAddress(startIpBytes);
        IPAddress endIp = new IPAddress(endIpBytes);

        List<IPAddress> addresses = new List<IPAddress>();

        for (IPAddress currentIp = startIp; ConvertIPv4AddressToUInt32(currentIp) <= ConvertIPv4AddressToUInt32(endIp); currentIp = IncrementIPAddress(currentIp))
        {
            addresses.Add(currentIp);
        }

        return addresses.ToArray();
    }
}

You could also implement the + and - operators for the IPAddress class, but since it wouldn't work for all uses of the class it's probably not a good idea.

public static IPAddress operator +(IPAddress address, int offset)
{
    if (address == null) throw new ArgumentNullException("address", "The value of address is a null reference.");
    if (address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork) throw new ArgumentException("The specified address's family is invalid.", "address");

    Byte[] addressBytes = address.GetAddressBytes();
    UInt32 addressInteger = (((UInt32)addressBytes[0]) << 24) + (((UInt32)addressBytes[1]) << 16) + (((UInt32)addressBytes[2]) << 8) + ((UInt32)addressBytes[3]);
    addressInteger += offset;
    addressBytes[0] = (Byte)((addressInteger >> 24) & 0xFF);
    addressBytes[1] = (Byte)((addressInteger >> 16) & 0xFF);
    addressBytes[2] = (Byte)((addressInteger >> 8) & 0xFF);
    addressBytes[3] = (Byte)(addressInteger & 0xFF);
    return new IPAddress(addressBytes);
}
public static IPAddress operator -(IPAddress address, int offset)
{
    if (address == null) throw new ArgumentNullException("address", "The value of address is a null reference.");
    if (address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork) throw new ArgumentException("The specified address's family is invalid.", "address");

    Byte[] addressBytes = address.GetAddressBytes();
    UInt32 addressInteger = (((UInt32)addressBytes[0]) << 24) + (((UInt32)addressBytes[1]) << 16) + (((UInt32)addressBytes[2]) << 8) + ((UInt32)addressBytes[3]);
    addressInteger -= offset;
    addressBytes[0] = (Byte)((addressInteger >> 24) & 0xFF);
    addressBytes[1] = (Byte)((addressInteger >> 16) & 0xFF);
    addressBytes[2] = (Byte)((addressInteger >> 8) & 0xFF);
    addressBytes[3] = (Byte)(addressInteger & 0xFF);
    return new IPAddress(addressBytes);
}

In your cycle you are doing some wild increments. First increment t is 0 so ip stays the same. Second increment t is 3 so 192.168.1.1 becomes 192.168.1.4 (and you save it as current). Third increment t is 6 so 192.168.1.4 becomes 192.168.1.10 (and saved as current) ...

I think what you are trying to achieve is somthing like this:

string from = "192.168.1.1", to = "192.168.1.255";
uint first = from.ToUInt(), last = to.ToUInt();

ulong total = last - first;
uint offset = 3; //This is an example number, it actually could be anything.

for (uint t = 0; (ulong)t < total; t += 1)
{
    uint ut = Convert.ToUInt32(t);
    uint c = first + t + offset;
    var ip = c.ToIPAddress();
} 

Ip can be decomposed as follow

integer value= (4thOctat*2^24.3rd*2^16.2nd*2^8.1st*2^0)

eg 64.233.187.99

64*2^24 + 233*2^16 + 187*2^8 + 99 = 1089059683

I wrote this small example for you,

    //This is regular expression to check the the ip is in correct format 
    private readonly Regex ip = new Regex(@"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");

    private void Main()
    {
        string IpAddress = "172.22.1.1";

        if (ip.IsMatch(IpAddress))
        {                
            //increment first octat by 5
            string IncrementedIp = IncrementIP(0, 100, IPAddress.Parse(IpAddress));
            if (ip.IsMatch(IncrementedIp))
            {
                Console.WriteLine("Incremented Ip = {0}", IncrementedIp);
            }
            else
            {
                //not valid ip address}
            }
        }else
        {
            //Not Valid Ip Address
        }

    }

    private string IncrementIP(short octat, long Offset,IPAddress adress)
    {
        //octat range from 0-3
        if ( octat<0 ||octat > 3) return adress.ToString();

        long IpLong = AdressToInt(adress.ToString());
        IpLong += (long)(Offset*(Math.Pow(2,octat*8)));
        return longToAddress(IpLong);
    }
    static long AdressToInt(string addr)
    {
        return (long)(uint)IPAddress.NetworkToHostOrder(
             (int)IPAddress.Parse(addr).Address);
    }

    static string longToAddress(long address)
    {
        return IPAddress.Parse(address.ToString()).ToString();
    }

To evaluate a little: You simply change the numeric representation of a value from one base to another, the another in this case being the 10-base, which your code, your head and your computer language use commonly. In 10-base, you can easily perform arithmetics. Once you have done that, you change the resulting number back to another base again, for example the original one.

In the case of an IP-address, the base is 256. As said earlier, an IP-address is simply a numeric value consisting 32 bits.

  • Bits are 2-base (toolset: 0,1)
  • Your calculation happens in 10-base (0,1,2,3,4,5,6,7,8,9)
  • Hexa is 16-base ((0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F)
  • An IP-address is (4 of) 256-base (0,1,2,3,4,5,6,7,8,9,[we should have another 246 unique symbols here]). As we do not have 256 unique numeric symbols (would be too many anyway), we describe these for convenience using 10-base instead, for example 253 (but 253 should really be the 254th symbol in a symbol table, like in the ASCII-table).

There are a million cases when you want to change base, or change numeric space. One example is incrementing a date. You change to the manageable days-since-20th-centurystart-space (the actual change isn't too simple, but the good result is a 10-base representation), perform the calculation (eg. increment with 7 days), and then change back to YMD-space.

The IP-address 255.255.255.255 could also be described using the 10-base integer value 4294967295.

They Answers are right... for addition to your implementation

CheckAgain:

If My.Computer.Network.Ping(CheckIPFirst) = False Then

'=====IF IP ADDRESS NOT OCCUPIED GET=========

CheckIPFirst +=1

GETIpAddress(Counter) = CheckIPFirst

Else

'======CHECK ANOTHER IP ADDRESS=============

CheckIPFirst +=1

Goto CheckAgain

End If

Through that you will not encounter a IP Address Conflict or Same IP Address.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM