sql server 和 oracle 中,ip與數字互轉
阿新 • • 發佈:2019-01-10
(一)Oracle中:
(1) IP轉為數字:
- createorreplacefunction ip2number(ip varchar2)
- return number
- is
- ip_num_hex varchar2(80);
- begin
- if (regexp_like(ip, '^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$')) then
-
ip_num_hex := lpad(trim(to_char(regexp_replace(ip, '^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$'
- lpad(trim(to_char(regexp_replace(ip, '^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$', '\2'), 'XX')),2,'0') ||
- lpad(trim(to_char(regexp_replace(ip, '^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$', '\3'), 'XX')),2,'0') ||
-
lpad(trim(to_char(regexp_replace(ip, '^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$'
- return to_number(ip_num_hex, 'XXXXXXXX');
- else
- return -1;
- end if;
- exception
- when others then
- return -99999999999;
- end;
- select ip2number('169.254.55.6') from dual;
- IP2NUMBER('169.254.55.6')
- -------------------------
- 2852009734
(2) 數字轉為IP:
- createorreplacefunction number2ip(num number)
- return varchar2 is
- ip_num_hex varchar2(8);
- begin
- ip_num_hex := lpad(trim(to_char(num, 'XXXXXXXX')), 8, '0');
- return to_number(substr(ip_num_hex, 1, 2), 'XX') || '.' ||
- to_number(substr(ip_num_hex, 3, 2), 'XX') || '.' ||
- to_number(substr(ip_num_hex, 5, 2), 'XX') || '.' ||
- to_number(substr(ip_num_hex, 7, 2), 'XX');
- exception
- when others then
- dbms_output.put_line(sqlerrm);
- returnnull;
- end;
- select number2ip(2852009734) from dual;
- NUMBER2IP(2852009734)
- --------------------------------------------------------------------------------
- 169.254.55.6
(二)SQL Server中:
(1) IP轉為數字:
- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_IP2Int]') and xtype in (N'FN', N'IF', N'TF'))
- dropfunction [dbo].[f_IP2Int]
- GO
- /*--字元型 IP 地址轉換成數字 IP
- /*--呼叫示例
- select dbo.f_IP2Int('192.168.0.11')
- select dbo.f_IP2Int('12.168.0.1')
- --*/
- CREATEFUNCTION f_IP2Int(
- @ip char(15)
- )RETURNSbigint
- AS
- BEGIN
- DECLARE @re bigint
- SET @re=0
- SELECT @[email protected]+LEFT(@ip,CHARINDEX('.',@ip+'.')-1)*ID
- ,@ip=STUFF(@ip,1,CHARINDEX('.',@ip+'.'),'')
- FROM(
- SELECT ID=CAST(16777216 asbigint)
- UNIONALLSELECT 65536
- UNIONALLSELECT 256
- UNIONALLSELECT 1)A
- RETURN(@re)
- END
- GO
(2) 數字轉為IP:
- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_Int2IP]') and xtype in (N'FN', N'IF', N'TF'))
- dropfunction [dbo].[f_Int2IP]
- GO
- /*--數字 IP 轉換成格式化 IP 地址
- /*--呼叫示例
- select dbo.f_Int2IP(3232235531)
- select dbo.f_Int2IP(212336641)
- --*/
- CREATEFUNCTION f_Int2IP(
- @IP bigint
- )RETURNSvarchar(15)
- AS
- BEGIN
- DECLARE @re varchar(15)
- SET @re=''
- SELECT @[email protected]+'.'+CAST(@IP/ID asvarchar)
- ,@[email protected]%ID
- from(
- SELECT ID=CAST(16777216 asbigint)
- UNIONALLSELECT 65536
- UNIONALLSELECT 256
- UNIONALLSELECT 1)a
- RETURN(STUFF(@re,1,1,''))
- END