IP地址与整型数字互转原理及多语言实现
在深入探讨具体实现之前,首先需要明确IP地址转换为整型(严格意义上应称为长整型)的基本原理。
【转换原理】:若设IP地址格式为 w.x.y.z,将其转化为整型数字的计算逻辑遵循以下公式:intIP = 256*256*256*w + 256*256*x + 256*y + z。
【PHP的互转】:PHP语言提供了便捷的内置函数来处理这一过程,主要包括 int ip2long ( string $ip_address ) 用于将IP转为整型,以及 string long2ip ( string $proper_address ) 用于反向转换,开发者可直接调用这两个函数完成操作。
【Asp的互转】:在Asp环境中需通过自定义函数实现,代码如下: '.-----------------------------------------------------------. '| describtion: 将IP转换为int型数字 | '| Authors: abandonship(http://jb51.net) | '~-----------------------------------------------------------~ Function IP2Num(ByVal strIP) Dim nIP Dim nIndex Dim arrIP arrIP = Split(strIP, ".", 4) For nIndex = 0 To 3 If Not nIndex = 3 Then arrIP(nIndex) = arrIP(nIndex) * (256 ^ (3 - nIndex)) End If nIP = nIP + arrIP(nIndex) Next IP2Num = nIP End Function '.-----------------------------------------------------------. '| describtion: 将int型数字转换为IP | '| Authors: abandonship(http://jb51.net) | '~-----------------------------------------------------------~ Function Num2IP(ByVal nIP) Dim strIP Dim nTemp Dim nIndex For nIndex = 3 To 0 Step -1 nTemp = Int(nIP / (256 ^ nIndex)) strIP = strIP & nTemp & "." nIP = nIP - (nTemp * (256 ^ nIndex)) Next strIP = Left(strIP, Len(strIP) - 1) Num2IP = strIP End Function
【MsSQL的互转】:MsSQL同样需要编写自定义函数,具体实现如下: /*************************************************************** * 将IP转换为int型数字 | * Code CreateBy abandonship(http://jb51.net) | **************************************************************/ CREATE FUNCTION [dbo].[ipToInt]( @strIp varchar(15) )RETURNS bigint AS BEGIN declare @nIp bigint set @nIp = 0 select @nIp = @nIp + LEFT( @strIp, charindex('.',@strIp+'.')-1)*Id from( select Id = cast(1*256*256*256 as bigint) union all select 1*256*256 union all select 1*256 union all select 1 ) as T return (@nIp) END /*************************************************************** * 将int型数字转换为IP | * Code CreateBy abandonship(http://jb51.net) | **************************************************************/ CREATE FUNCTION [dbo].[intToIP]( @nIp bigint )RETURNS varchar(15) As BEGIN declare @strIp varchar(15) set @strIp = '' select @strIp = @strIp +'.'+ cast(@nIp/ID as varchar), @nIp = @nIp%ID from( select ID = cast(1*256*256*256 as bigint) union all select 1*256*256 union all select 1*256 union all select 1 ) as T return(stuff(@strIp,1,1,'')) END
【MySQL的互转】:相较于MsSQL,MySQL的处理方式更为简便,其机制与PHP类似,均提供了内置函数支持。使用 select INET_ATON (IP地址) 可将IP转为整型,而使用 select INET_NTOA ( IP的整型数值 ) 则可完成反向转换,直接调用即可。