Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort list of Ip Addresses using c#

Tags:

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 
like image 503
Cracker Avatar asked Jun 06 '11 05:06

Cracker


People also ask

How do you sort IP addresses?

Approach: The idea is to use a custom comparator to sort the given IP addresses. Since IPv4 has 4 octets, we will compare the addresses octet by octet. Check the first octet of the IP Address, If the first address has a greater first octet, then return True to swap the IP address, otherwise, return False.

How do I sort IP address in Linux?

Sort first by the first field, and only the first field ( -k 1,1 ), then by the second and only the second ( -k 2,2 ), and so on ( -k 3,3 -k 4,4 ). Or, as I mentioned above, just use sort -V .


2 Answers

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(); 
like image 173
Alex Aza Avatar answered Sep 20 '22 14:09

Alex Aza


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.

like image 30
ColinE Avatar answered Sep 21 '22 14:09

ColinE