首先我們要先瞭解一下IP地址轉換為整型(嚴格來說應該說是長整型)的原理~
【轉換原理】:假設IP為:w.x.y.z,則IP地址轉為整型數位計算公式為:intIP = 256*256*256*w + 256*256*x + 256*y + z
【PHP的互轉】:PHP的轉換方式比較簡單,它內建了兩個函數
int ip2long ( string $ip_address )和 string long2ip ( string $proper_address )
可以直接調用使用~
【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的互轉】:自訂函數如下,
/***************************************************************
* 將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一樣也內建了兩個函數
IP轉為整型: select INET_ATON (IP地址) 和 整型轉為IP: select INET_NTOA ( IP的整型數值 )
可以直接調用使用~