qileilove

          blog已經(jīng)轉(zhuǎn)移至github,大家請訪問 http://qaseven.github.io/

          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ù)庫

          <2014年8月>
          272829303112
          3456789
          10111213141516
          17181920212223
          24252627282930
          31123456

          導(dǎo)航

          統(tǒng)計

          常用鏈接

          留言簿(55)

          隨筆分類

          隨筆檔案

          文章分類

          文章檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 昔阳县| 蒲城县| 平度市| 丹寨县| 黔东| 卢氏县| 清镇市| 上虞市| 衡阳县| 北碚区| 石屏县| 吴忠市| 秦安县| 盐源县| 武隆县| 沙洋县| 增城市| 卢氏县| 永丰县| 平谷区| 普安县| 成武县| 文水县| 丹巴县| 鄄城县| 克拉玛依市| 临颍县| 连山| 崇义县| 九龙城区| 高青县| 榕江县| 凌海市| 新宁县| 镇远县| 石河子市| 额尔古纳市| 筠连县| 庆阳市| 翼城县| 如东县|