根据IP和掩码 计算起止IP和主机数的 MSSQL函数,输入主机IP和掩码位数后,能返回对应的起始IP和结束IP。比如,输入IP:101.32.0.0,MASK:12 (即:101.32.0.0/12),则可以得到101.32.0.1到101.47.255.254这个范围。现前有人写过一段代码 但是测试结果基本无意义无法使用,代码入下,希望 有高手能解决这个问题
create function f_cip(@ip varchar(30),@mask int)
returns varchar(300)
as
begin
declare @i int,@ret varchar(300)
set @i = 1
set @mask = 256 - @mask
while power(2,@I) < @mask
set @i = @I + 1
set @mask = power(2,@i)
set @i = 256/@mask
while @i > 0
begin
set @ret =isnull(@ret+char(13),'')+'192.168.0.'+right('000'+ltrim((@i-1)*@mask),3) + '-----'+'192.168.0.'+ltrim(@i*@mask - 1)
set @I = @I- 1
end
return @ret
end
go
declare @ip varchar(30)
declare @m int
set @m = 200
set @ip = '192.168.0.0'
select dbo.f_cip(@ip,@m) as '所有子网'
drop function f_cip
------解决思路----------------------
你的题目没有考虑分子网情况 ,所以大概可有如下代码
create function f_bin2int(@bin varchar(8),@type int)--@type 前补零or后补零
returns varchar(4)
as
begin
declare @i varchar(8),@ret int,@c int
set @i = '00000000'
if (@type = 0)
select @i = REVERSE (stuff(@i,1,len(@bin),@bin))
else
select @i = REVERSE (stuff(@i,9 - len(@bin),8,@bin))
set @c = 1
set @ret = 0
while @c <= 8
begin
if substring(@i ,@c,1) = '1'
set @ret = @ret +power(2,@c-1)
set @c = @c + 1
end
return convert(varchar(3),@ret)
end
go
create function f_int2bin(@i int)
returns varchar(1000)
as
begin
declare @s varchar(1000)
set @s=''
while @i>0
select @s=cast(@i%2 as varchar)+@s
,@i=@i/2
return(@s)
end
go
create function f_cip1(@mask int)--@mask掩码位
returns varchar(30)
as
begin
declare @i int,@temp varchar(300),@ret varchar(300)
set @i = 0
set @temp = REPLICATE('1',@mask)+REPLICATE('0',32 - @mask)
set @ret = ''
while @i <4
begin
set @ret = @ret+dbo.f_bin2int(substring(@temp,@i*8+1,8),0)
set @i = @i + 1
if @i < 4 set @ret = @ret +','
end
return @ret
end
go
create function f_cip2(@ip varchar(30),@mask int)--@mask掩码位
returns varchar(40)
as
begin
declare @r varchar(40),@ret varchar(40),@ret1 varchar(40)
declare @i int
set @i = 1
set @r = ''
set @ip =@ip + '.'
set @ret = ''
set @ret1= ''
while (charindex('.',@ip,1) > 0)
begin
set @i = charindex('.',@ip,1)
set @r = dbo.f_int2bin(cast(left(@ip,@i - 1) as bigint))
set @ret = @ret +REPLICATE('0',8-len(@r))+@r
set @ip = right(@ip ,len(@ip) - @i)
end
set @i = 0