PHP Asp MsSQL MySQL methods for converting IP addresses to integer Numbers

  • 2020-07-21 07:10:20
  • OfStack

First, we need to understand the principle of IP address conversion to integer (strictly speaking, long integer)

[Conversion principle] : If IP is: w.x.y.z, then the calculation formula of IP address to integer number is: intIP = 256*256*256*w + 256*x + 256*y + z

PHP: PHP has two built-in functions
int ip2long (string $ip_address) and string long2ip (string $proper_address)
Can be called directly using ~

[Asp interchange] : The custom function is as follows,
'.-----------------------------------------------------------.
'| describtion: converts IP to int type |
'| Authors: abandonship(http://ofstack.com) |
'~-----------------------------------------------------------~
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: converts the type int number to IP |
'| Authors: abandonship(http://ofstack.com) |
'~-----------------------------------------------------------~
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 interchange] : The custom function is as follows,
/***************************************************************
* convert IP to int type number |
* Code CreateBy abandonship(http://ofstack.com) |
**************************************************************/
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

/***************************************************************
* convert int type Numbers to IP |
* Code CreateBy abandonship(http://ofstack.com) |
**************************************************************/
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 intertransformation] : MySQL is simpler than MsSQL in that it has two built-in functions like PHP1
IP converted to integer: select INET_ATON (IP address) and integer converted to IP: select INET_NTOA (IP integer value)
Can be called directly using ~


Related articles: