Sorting IP Addresses with Coldfusion
I am creating an application to store IP Address information in it. However, sorting the IP Addresses has brought up a challenge.
I have 5 columns with Status, IP, Node Name, Comments, and Date. Sorting the columns is a piece of cake, but when I sort the IP column by IPs do something like this:
12.34.56.1
12.34.56.100
12.34.56.101
12.34.56.2
12.34.57.1
12.34.57.100
12.34.57.101
12.34.57.3
....
12.34.56.100
12.34.56.101
12.34.56.2
12.34.57.1
12.34.57.100
12.34.57.101
12.34.57.3
....
What I want is this:
12.34.56.1
12.34.56.2
12.34.56.100
12.34.56.101
12.34.57.1
12.34.57.3
12.34.57.100
12.34.57.101
....
12.34.56.2
12.34.56.100
12.34.56.101
12.34.57.1
12.34.57.3
12.34.57.100
12.34.57.101
....
Any ideas?
***EDIT I didn't want this to get lost in the comments, so here is the solution (for MySQL) I converted from the Internet host address into binary data using function called "INET_ATON".
Example:
SELECT INET_ATON(ipAddress)AS binary_ip, ipAddress
FROM ip_addresses
ORDER BY binary_ip;
SELECT INET_ATON(ipAddress)AS binary_ip, ipAddress
FROM ip_addresses
ORDER BY binary_ip;

<code>
<cfset ipaddy = "10.98.128.2">
<cfset ipArray = ArrayNew(1)>
<cfset ipArray[1] = ListGetAt(ipaddy, 1, ".")>
<cfset ipArray[2] = ListGetAt(ipaddy, 2, ".")>
<cfset ipArray[3] = ListGetAt(ipaddy, 3, ".")>
<cfset ipArray[4] = ListGetAt(ipaddy, 4, ".")>
<cfoutput>
#NumberFormat(ipArray[1],'000')#.#NumberFormat(ipArray[2],'000')#.#NumberFormat(ipArray[3],'000')#.#NumberFormat(ipArray[4],'000')#
</cfoutput>
</code>
I hope my code above shows up correctly.
So I thought I'd come up with the most long rounded way possible. This involves converting the IP Address to a decimal string, and uses 2 UDFs.. quite silly really. I'm sure there's a solution in one line...
Source code here:
http://www.oxalto.co.uk/demos/sortip.cfm
http://office.microsoft.com/en-us/access/HP0116461...
AND here:
http://www.dbforums.com/showthread.php?t=585462
Based on those you could probably come up with a purely SQL way of getting the sort you want.
I would add 4 columns to your DB for each octal of the IP and then sort them accordingly.
Example:
SELECT INET_ATON(ipAddress)AS binary_ip, ipAddress
FROM ip_addresses
ORDER BY binary_ip;