Given List<string> ips = new List<string>();
I need to sort the list of IP addresses in a logical order (i.e. "192.168.0.2" comes before "192.168.0.100").
Currently (and correctly, alphabetically) if the list contains:
192.168.0.1
192.168.0.2
192.168.0.10
192.168.0.200
ips.OrderBy(p => p)
returns:
192.168.0.1
192.168.0.10
192.168.0.2
192.168.0.200
I would create a comparer for
System.Net.IPAddress
like soand then proceed as follows:
I wrote an IpComparer for IPv6. The variant from Howel doesn't work.
Here is the Comparer:
And here a unit test:
I hope this solution is correct. I'm not an expert in IPv6.
You need to make a comparer: (Tested)
You can then write
You could split this into 4 integer values, and sort by each in turn:
This one is pretty elegant (and fail proof if you use
TryParse
):The
addressBytes
array will have length 4 as long as it is only IP4 addresses. Otherwise you should account for the length...This is an old question but I was looking up IP Comparer's and it came up. I wanted something that worked for IPv6 as well though so once I got it I thought I'd add it here for the next person who does a search for it. Much like SLaks's answer, I agree that an IComparer is probably best.
Nothing fancy but it should work.