Oracle中IP地址和掩碼轉(zhuǎn)換成CIDR格式
遇到的問題如下:數(shù)據(jù)庫中存儲了IP地址,以及IP地址掩碼,需要將他們轉(zhuǎn)化成CIDR格式的,并且不僅僅是將掩碼轉(zhuǎn)化成CIDR對應(yīng)的數(shù)字的問題,需要將原有的IP地址轉(zhuǎn)化成對應(yīng)的網(wǎng)絡(luò)地址,例如IP地址是58.247.221.238,掩碼是255.255.255.252,需要將其轉(zhuǎn)化為58.247.221.236/30。
解決方案:我們知道,將IP地址和掩碼通過位與函數(shù)就能得到對應(yīng)的網(wǎng)絡(luò)地址.Google一下,找到了將IPv4地址轉(zhuǎn)成數(shù)字以及轉(zhuǎn)化回來的函數(shù)。有了這兩個函數(shù),再利用Oracle 自帶的bitand函數(shù),問題就解決了。可以先將IP地址和掩碼通過字符串轉(zhuǎn)IP的函數(shù)轉(zhuǎn)成數(shù)字,然后通過位與運(yùn)算就能得到相應(yīng)的網(wǎng)絡(luò)地址對應(yīng)的數(shù)字,再通過數(shù)字轉(zhuǎn)字符串的功能,即得到對應(yīng)的網(wǎng)絡(luò)地址。至于/后面CIDR的數(shù)字,可以通過導(dǎo)入一張掩碼和CIDR數(shù)字的對應(yīng)表得到,不在詳述.
實(shí)際例子如下: 返回58.247.221.236
Sql代碼
select inttoip(BITAND(dottedQuadToNumber('58.247.221.238'),
ottedQuadToNumber('255.255.255.252'))) from dual
附: 將字符串轉(zhuǎn)成數(shù)字的函數(shù):
Sql代碼
CREATE OR REPLACE function dottedQuadToNumber ( dottedQuad IN VARCHAR2) return number is Result NUMBER; begin Result:= (substr(dottedQuad , 1, (instr(dottedQuad , '.', 1, 1 ) - 1)) * 256 * 256 * 256 ) + (substr(dottedQuad , instr(dottedQuad , '.', 1, 1 ) + 1, instr(dottedQuad , '.', 1, 2 ) - instr(dottedQuad , '.', 1, 1 ) - 1) * 256 * 256 ) + (substr(dottedQuad , instr(dottedQuad , '.', 1, 2 ) + 1, instr(dottedQuad , '.', 1, 3 ) - instr(dottedQuad , '.', 1, 2 ) - 1) * 256 ) + (substr(dottedQuad , instr(dottedQuad , '.', 1, 3 ) + 1) ) ; return(Result ); end dottedQuadToNumber ; |
數(shù)字轉(zhuǎn)成ip地址的函數(shù):
Sql代碼
CREATE OR REPLACE function inttoip(ip_address integer) return varchar2 deterministic is begin return to_char(mod(trunc(ip_address /256/ 256/256 ),256)) || '.'|| to_char(mod(trunc(ip_address/ 256/256 ),256)) || '.'|| to_char(mod(trunc(ip_address/ 256),256 )) || '.'|| to_char(mod(ip_address, 256)); end; |
posted on 2014-08-04 09:58 順其自然EVO 閱讀(265) 評論(0) 編輯 收藏 所屬分類: 數(shù)據(jù)庫