Convert IPs to Integers

More fun with IPs, this time converting them to integers.

<cffunction name="IPtoInt" output="false" returntype="struct"
   hint="Returns a struct with two nodes<br />
   Start: The starting IP address for the range specified<br />
   End: The last IP address in the range
   Range: Number of IP Addresses in the range"

>
   <cfargument name="IPAddress" type="string" required="true" hint="" />

   <cfset var LOCAL = StructNew() />
   <cfset LOCAL.retVal = StructNew() />
   <cfset LOCAL.retVal.range = 0 />
   <cfif ListLen(Arguments.IPAddress, ".") LT 4>
      <cfset LOCAL.retVal.range = 255^(4-ListLen(Arguments.IPAddress, ".")) />
      <cfloop from="1" to="#4-ListLen(Arguments.IPAddress, ".")#" index="LOCAL.i">
         <cfset Arguments.IPAddress &= ".0" />
      </cfloop>
   </cfif>

   <cfset LOCAL.Octets = ListToArray(Arguments.IPAddress, ".") />
   <cfloop array="#LOCAL.Octets#" index="LOCAL.octet">
      <cfif LOCAL.octet LT 0 OR LOCAL.octet GT 255>
         <cfthrow
            type="exception"
            message="Invalid Octet"
            detail="The octet '#LOCAL.octet#' is outside acceptable range. Octets must between 0 and 255." />

      </cfif>
   </cfloop>

   <cfif LOCAL.Octets[1] LT 128>
      <cfset LOCAL.base = LOCAL.Octets[1] * 16777216 />
   <cfelse>
      <cfset LOCAL.base = -(256 - LOCAL.Octets[1]) * 16777216 />
   </cfif>

   <cfset LOCAL.retVal.Start = LOCAL.base + (LOCAL.Octets[2] * 65536) + (LOCAL.Octets[3] * 256) + (LOCAL.Octets[4]) />
   <cfset LOCAL.retVal.End = LOCAL.retVal.Start + LOCAL.retVal.Range />

   <cfreturn LOCAL.retVal />

</cffunction>

0 responses to “Convert IPs to Integers”

Leave a Reply

Leave this field empty:

Powered by Mango Blog.