ColdFusion IPv6 to 128-bit unsigned int

2019-10-03 04:15发布

问题:

I needed to create a function that could convert an IPv6 address to its numeric representation.

Working with IPv4 is pretty straight forward as it uses an 32-bit unsigned int for its numerical representation. IPv6 is represented by an 128-bit unsigned int. That size of a number is too large for the builtin ColdFusion bit logic functions to use.

This function must make use of the underlying Java system to make the conversion.

Need a function to do the reverse: ColdFusion 128-bit unsigned int to IPv6

回答1:

This is the function that I wrote to transform an IPv6 address to a 128-bit unsigned int.

<cffunction name="IPv6ToUInt128" returntype="numeric" output="no" access="public" hint="returns uint128 number for IPv6 address">
    <cfargument name="vcIPv6" type="string" required="yes" hint="IPv6 address">

    <cfif arguments.vcIPv6 EQ "">
        <cfreturn 0>
    </cfif>

    <cfset local['javaMathBigInteger'] = CreateObject("java", "java.math.BigInteger")>
    <cfset local['javaNetInetAddress'] = CreateObject("java", "java.net.InetAddress")>
    <cftry>
        <cfset local['uint128'] = local.javaMathBigInteger.init(1, local.javaNetInetAddress.getByName(arguments.vcIPv6).getAddress()).toString()>
        <cfreturn local.uint128>
        <cfcatch type="any">
            <cfreturn 0>
        </cfcatch>
    </cftry>
</cffunction>

If you have any suggestions to improve this code, please leave comments.