Question

i am using pcapdotnet DLL's in my application and one of the option i have added is to change the packet ip address before sending the pcap file (send to my function 2 ip's: old ip address and the new ip address i want to change).

now i want to add another option that can change range of ip address.

for example:

old ip addreee is 70.1.2.3 and the range is 10.0.0.1 until 212.0.0.0

so the ip address 70.1.2.3 will change to 10.0.0.1 and than 10.0.0.2 up to 70.1.2.3 and i am looking the best way to do it.

so far i only see this post who did not help me: Is there easy way of calculating number of IPs from 2 given IP addresses?

Was it helpful?

Solution

  1. An IPv4 address consists of 4 bytes, and combining these 4 bytes gives you a plain 32-bit number. You can easily get this number using the method described in the thread you linked (I just noticed @DarkSquirrel42 already posted the same answer while I was meddling around). The only thing I would change in that answer is to return an unsigned integer (uint):

    public static uint IPToInt(string IP)
    {
         return (uint)IPAddress.NetworkToHostOrder(
             BitConverter.ToInt32(IPAddress.Parse(IP).GetAddressBytes(), 0));
    }
    
  2. Once you have it, it's a matter of simple math:

    Map a range of IP numbers to a different range of IP numbers

    Note that 10.0.0.1 to 212.0.0.0 is a very large range. If you map 10.0.0.1 to 70.1.2.3, you will run out of address space before you get to 212.0.0.0.

OTHER TIPS

the post that "did not help" has all you need:

it shows you how to transform an IPv4 in three-dotted-form into an Int32 (that works because an IPv4 address is exactly 32 bits in size)

from there you can simply start counting

what you want to do looks like:

transform your IP range into 2 32-Bit integers

do a for loop from one to the other

transform the loop variable back into three-dotted-form

optionally check for IPs that should not be used and skip them (in case of classless IP ranges you might want to exclude IPs that would be network or broadcast addresses in classfull ranges...)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top