当前位置: 移动技术网 > IT编程>开发语言>PHP > 将IP地址转换为整型数字的PHP方法、Asp方法和MsSQL方法、MySQL方法

将IP地址转换为整型数字的PHP方法、Asp方法和MsSQL方法、MySQL方法

2019年05月24日  | 移动技术网IT编程  | 我要评论

首先我们要先了解一下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的整型数值 )
可以直接调用使用~

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网