How to sort list of Ip Addresses using c#
10,553
Solution 1
This might look as a hack, but it does exactly what you need:
var unsortedIps =
new[]
{
"192.168.1.4",
"192.168.1.5",
"192.168.2.1",
"10.152.16.23",
"69.52.220.44"
};
var sortedIps = unsortedIps
.Select(Version.Parse)
.OrderBy(arg => arg)
.Select(arg => arg.ToString())
.ToList();
Solution 2
You can convert each IP address into an integer like so ...
69.52.220.44 =>
69 * 255 * 255 * 255 +
52 * 255 * 255 +
220 * 255 +
44
Then sort by the integer representation.
Solution 3
You may find this function useful too.
public static class ExtensionMethods
{
public static int CompareTo(this IPAddress x, IPAddress y)
{
var result = x.AddressFamily.CompareTo(y.AddressFamily);
if (result != 0)
return result;
var xBytes = x.GetAddressBytes();
var yBytes = y.GetAddressBytes();
var octets = Math.Min(xBytes.Length, yBytes.Length);
for (var i = 0; i < octets; i++)
{
var octetResult = xBytes[i].CompareTo(yBytes[i]);
if (octetResult != 0)
return octetResult;
}
return 0;
}
}
Related videos on Youtube
Author by
Cracker
Updated on December 15, 2020Comments
-
Cracker over 3 years
I've a list of IP addresses as follows
192.168.1.5 69.52.220.44 10.152.16.23 192.168.3.10 192.168.1.4 192.168.2.1
I'm looking for such a way to sort this list to match the below order
10.152.16.23 69.52.220.44 192.168.1.4 192.168.1.5 192.168.2.1
-
JED HK almost 13 yearsThis will give you "10.152.16.23","192.168.1.4", "192.168.1.5", "192.168.2.1", "69.52.220.44"
-
Alex Aza almost 13 years@Norbert - please try the code before stating that. I actually checked the result before posting.
-
Cracker almost 13 years@Alex nice solution, thnx Man
-
Miki Watts over 12 years@Alex that's actually a brilliant idea, thanks, it saved me time
-
Falko over 7 yearsA more compact version:
unsortedIps.OrderBy(Version.Parse).ToList()
. -
Steven Rands about 7 yearsJust a note that the
Version.Parse
method was only added in .Net Framework 4, so if using an earlier version of the framework this solution will not work. -
Patrick Mevzek over 5 yearsBy that computation
0.0.0.255
has same value as0.0.1.0
where they should be different. The multiplier should be 256, not 255. See from Wikipedia: "For example, the quad-dotted IP address 192.0.2.235 represents the 32-bit decimal number 3221226219".192.0.2.235
=>192*256*256*256 + 2*256 + 235
= 3221226219 indeed where if you use above formula you get192*255*255*255 + 2*255 + 235
= 3183624745 -
BetterLateThanNever over 4 yearsSystem.Net.IPAddress.Parse is something that we can try in place of Version.Parse
-
tolsen64 over 4 yearsI had a
List<IPAddress>
and sorted it like this:lstIp = lstIp.OrderBy(i => new Version(i.ToString())).ToList();
-
Riwels over 3 years@PatrickMevzek is right. A byte has 256 values and you should multiply for the number of values, not the higher one.
-
thinkOfaNumber almost 3 yearsMake sure you use 32-bit unsigned ints!