2017-04-04 71 views
-2

我已經張貼這將IPv6地址轉換爲128位無符號整型值這裏的函數:ColdFusion IPv6 to 128-bit unsigned intColdFusion的128位無符號整型向IPv6

我需要一個函數,將現在在另一個方向走。

這個功能變得更加複雜,我將解釋答案中的複雜問題。

+1

http://codereview.stackexchange.com/也許? – Henry

+0

顯然。有人要求從另一個問題看這些功能。這種東西(負面評級沒有任何解釋)*真正*使一個人不想貢獻。 –

回答

0

以下是將128位無符號整數轉換爲具有正確(簡潔)IPv6格式的IPv6地址的函數。

說明: 像這樣的函數的部分問題是傳入函數(nUInt128)的數字不能保證是一個128位無符號整數。它可能是8位(:: 1),甚至像一個有符號的136位數字(ColdFusion/Java似乎更喜歡signed int)的奇怪東西。如果沒有完全轉換爲具有16個值的Java Byte數組的128位數字,將導致java.net.Inet6Address.getAddress()拋出錯誤。我的解決方案是創建一個包含16個零的ColdFusion數組,然後將其填充,然後將其用於java.net.Inet6Address.getAddress()。我很驚訝,因爲我不知道這個數字有多大。 ColdFusion/Java以某種方式做了一些魔術,並將數組變成了Byte []。回填也會去除更大的數字並修復136位signed int問題。

<cffunction name="UInt128ToIPv6" returntype="string" output="no" access="public" hint="returns IPv6 address for uint128 number"> 
    <cfargument name="nUInt128" type="numeric" required="yes" hint="uint128 to convert to ipv6 address"> 

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

    <cftry> 
     <cfset local['javaMathBigInteger'] = CreateObject("java", "java.math.BigInteger").init(arguments.nUInt128)> 
     <cfset local['JavaNetInet6Address'] = CreateObject("java", "java.net.Inet6Address")> 
     <cfset local['arrBytes'] = local.javaMathBigInteger.toByteArray()> 

     <!--- correct the array length if !=16 bytes ---> 
     <cfset local['arrFixedBytes'] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]> 
     <cfif arrayLen(local.arrBytes) NEQ 16> 
      <cfset local['nFixedIndex'] = 16> 
      <cfset local['nBytesIndex'] = arrayLen(local.arrBytes)> 

      <cfloop condition="local.nFixedIndex NEQ 0 && local.nBytesIndex NEQ 0"> 
       <cfset local.arrFixedBytes[local.nFixedIndex] = local.arrBytes[local.nBytesIndex]> 
       <cfset local.nFixedIndex--> 
       <cfset local.nBytesIndex--> 
      </cfloop> 
     </cfif> 
     <!--- /correct the array length if !=16 bytes ---> 

     <cfif arrayLen(local.arrBytes) NEQ 16> 
      <cfset local['vcIPv6'] = local.JavaNetInet6Address.getByAddress(local.arrFixedBytes).getHostAddress()> 
     <cfelse> 
      <cfset local['vcIPv6'] = local.JavaNetInet6Address.getByAddress(local.javaMathBigInteger.toByteArray()).getHostAddress()> 
     </cfif> 
     <cfcatch type="any"> 
      <cfset local['vcIPv6'] = ""> 
     </cfcatch> 
    </cftry> 

    <cfreturn formatIPv6(vcIPv6 = local.vcIPv6)> 
</cffunction> 

這裏是formatIPv6()效用函數,它在前一個函數的末尾被調用。

<cffunction name="formatIPv6" returntype="string" output="yes" access="public" hint="returns a compressed ipv6 address"> 
    <cfargument name="vcIPv6" type="string" required="yes" hint="IPv6 address"> 

    <!--- inside reReplace removes leading zeros, outside reReplace removes repeating ":" and "0:" ---> 
    <cfreturn reReplace(reReplace(LCase(arguments.vcIPv6), "(:|^)(0{0,3})([1-9a-f]*)", "\1\3", "all"), "(^|:)[0|:]+:", "::", "all")> 
</cffunction> 

如果您有任何建議/問題,請發表評論。

+0

恕我直言,這應該在'' –

+0

更好的表現? –

+0

減少打字並且更易於閱讀。 –