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
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.
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 .
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With