Set ansi_nulls on
Set quoted_identifier on
Go
/**********************************
* Function: convert an IP address to a binary value.
* Date: 2009-07-27
* Author:
* Test: Select getipbinary ('2017. 0.0.1)
**********************************/
Alter function [DBO]. [getipbinary] (@ IP varchar (32 ))
Returns nvarchar (32)
As
Begin
Declare @ ipresult varchar (50) -- returned result
Declare @ IPaddress varchar (9) -- extracted IP Address
Declare @ index int -- get the index.
Declare @ Yushu varchar (10) -- Record Remainder
Declare @ Shang int -- the operator obtained after Division
Declare @ jieguo varchar (30) -- converted result
Declare @ count int
Set @ COUNT = 0
Set @ Index = patindex ('%. %', @ IP)-1
Set @ ipresult =''
While (@ index> 0)
Begin
Set @ IPaddress = substring (@ IP, 1, @ index)
Set @ jieguo =''
-- Convert to 8-bit binary
If (cast (@ IPaddress as INT) = 0)
Begin
Set @ jieguo = '000000'
End
While (cast (@ IPaddress as INT)> 0)
Begin
Set @ Yushu = @ IPaddress % 2
Set @ Shang = @ IPaddress/2
Set @ IPaddress = @ Shang
Set @ jieguo = @ Yushu + @ jieguo
End
While (LEN (@ jieguo) <> 8)
Set @ jieguo = '0' + @ jieguo
Set @ ipresult = @ ipresult + @ jieguo
Set @ IP = substring (@ IP, @ index + 2, Len (@ IP ))
Set @ COUNT = @ count + 1
If (@ count <= 2)
Set @ Index = patindex ('%. %', @ IP)-1
Else
Set @ Index = Len (@ IP)
End
Return @ ipresult
End