ColdFusion UDFs long2ip() and ip2long()

Yesterday I was working on porting some PHP code into ColdFusion. The PHP code was using a function called long2ip(), and I researched this PHP Manual website to learn more about it. I needed this function in CF, but couldn't find it at cflib or anywhere else doing a few Google searches. The closest I came was this blog post by Brandon Purcell, which got me started in the right direction. I learned from what Brandon wrote, along with the comments input by Gabriel Malca (if the function doesn't exist) at the PHP Manual site and came up with the logic for my CF version of the function. After I had this working, I figured I better implement the opposite conversion function as well, so I also created ip2long(). Again I found a user comment for when the function doesn't exist to base my function's logic. I submitted these to cflib.org today, so look for them soon.

Examples:
long2ip(3401190660) = 202.186.13.4
ip2long(202.186.13.4) = 3401190660

Here is the code for UDFs below:

<cfscript>
/**
* Generates an (IPv4) Internet Protocol dotted address (aaa.bbb.ccc.ddd) from the proper address representation. Returns 0 if error occurs.
*
* @param longip Numeric value of the address you want to convert. (Required)
* @return Returns a String.
* @author Troy Pullis (tpullis@yahoo.com)
* @version 1, Jan 5, 2009
*/
function long2ip(longip)
{
   var ip = "";
   var i = "";
if (longip < 0 || longip > 4294967295)
      return 0;
for (i=3;i>=0;i--) {
ip = ip & int(longip / 256^i);
longip = longip - int(longip / 256^i) * 256^i;
if (i>0)
         ip = ip & ".";
}
return ip;
}

/**
* Converts a string containing an (IPv4) Internet Protocol dotted address (aaa.bbb.ccc.ddd) into a proper address representation. Returns 0 if error occurs.
*
* @param ip Dotted address value you want to convert. (Required)
* @return Returns a String.
* @author Troy Pullis (tpullis@yahoo.com)
* @version 1, Jan 5, 2009
*/
function ip2long(ip) {
   var iparr = ListToArray(ip,".");
   if (ArrayLen(iparr) != 4)
      return 0;
   else
       return iparr[1]*256^3 + iparr[2]*256^2 + iparr[3]*256 + iparr[4];
}
</cfscript>

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
BlogCFC was created by Raymond Camden. This blog is running version 5.9.002. Contact Blog Owner