jsakamoto / ipaddressrange

.NET Class Library for range of IP address, both IPv4 and IPv6.
Mozilla Public License 2.0
370 stars 71 forks source link

[Question] How do I find out a number of addresses in a given range? #62

Closed AndrewSav closed 3 years ago

AndrewSav commented 4 years ago

This takes 7 seconds on my i5:

    NetTools.IPAddressRange a = NetTools.IPAddressRange.Parse("10.0.0.0/8");
    a.AsEnumerable().Count();

Is there a faster way?

jsakamoto commented 4 years ago

Unfortunately, this library doesn't provide the feature that returns how many addresses in the range, at this time.

Instead, you can calculate it on your own way.

For example, if the type of address is IPv4 and the type of representation of the range is CIDR, you can get the number of addresses from bitmask length, like this.

2 ^ (32 - {bitmask length})

For example, if the bitmask length is 8 (from "10.0.0.0/8"), the C# code will be as below.

> Math.Pow(2, 32 - 8)
16777216

if the type of address is IPv4 and the type of representation of the range is begin-end (ex: "192.168.0.10-192.168.3.22"), you can get the number of addresses in the range by simple subtraction of UInt32 values, because IPv4 address can convert to simple UInt32 value.

For example, the C# code will be as below.

> var a = BitConverter.ToUInt32(IPAddress.Parse("192.168.0.10").GetAddressBytes().Reverse().ToArray(), 0);
> var b = BitConverter.ToUInt32(IPAddress.Parse("192.168.3.22").GetAddressBytes().Reverse().ToArray(), 0);
> b - a
780

I hope this reply is helpful to you.

AndrewSav commented 4 years ago

Thank you. Any plans to provide that as part of the library? I think that would be an improvement. Also looking at the code this could be probably significantly improved (performance-wise), would you consider that?

jsakamoto commented 4 years ago

Yes, you are right. The current implementation of this library is very Inefficiency, as you know.

Of course, I know that I can improve this library for more efficiency. (for example, I can rewrite it to use an IPv4 address as a single UInt32 value instead of a byte array.) But I had never started that work in some untechnical personal reason.

However, your comment might be a big chance for me to be started the improvement of this library.

I can't promise that when is the day of the new version release, but anyway, I'll try to do it! 😄

jsakamoto commented 4 years ago

Progress Report

I published a v.4.1 preview version.

This version is improved performance for the IPv4 address range operations.

The result of benchmark for ...AsEnumerable().Count() operation is below.

image

It improved from 7 seconds to 1.6 microseconds. 😄

I'll also continue to improve performance for an IPv6 address range operations, as I can.

jsakamoto commented 4 years ago

I published v.4.1.0 officially. 🎉

It includes the performance improvements about enumeration and counting it, not only IPv4 but also IPv6.

Please try it out.