qileilove

          blog已經轉移至github,大家請訪問 http://qaseven.github.io/

          Oracle中IP地址和掩碼轉換成CIDR格式

            遇到的問題如下:數據庫中存儲了IP地址,以及IP地址掩碼,需要將他們轉化成CIDR格式的,并且不僅僅是將掩碼轉化成CIDR對應的數字的問題,需要將原有的IP地址轉化成對應的網絡地址,例如IP地址是58.247.221.238,掩碼是255.255.255.252,需要將其轉化為58.247.221.236/30。
            解決方案:我們知道,將IP地址和掩碼通過位與函數就能得到對應的網絡地址.Google一下,找到了將IPv4地址轉成數字以及轉化回來的函數。有了這兩個函數,再利用Oracle 自帶的bitand函數,問題就解決了。可以先將IP地址和掩碼通過字符串轉IP的函數轉成數字,然后通過位與運算就能得到相應的網絡地址對應的數字,再通過數字轉字符串的功能,即得到對應的網絡地址。至于/后面CIDR的數字,可以通過導入一張掩碼和CIDR數字的對應表得到,不在詳述.
            實際例子如下: 返回58.247.221.236
            Sql代碼
            select inttoip(BITAND(dottedQuadToNumber('58.247.221.238'),
            ottedQuadToNumber('255.255.255.252'))) from dual
            附: 將字符串轉成數字的函數:
            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 ;
            數字轉成ip地址的函數:
            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 閱讀(263) 評論(0)  編輯  收藏 所屬分類: 數據庫

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

          導航

          統計

          常用鏈接

          留言簿(55)

          隨筆分類

          隨筆檔案

          文章分類

          文章檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 金湖县| 军事| 郎溪县| 油尖旺区| 马关县| 和林格尔县| 海伦市| 宝丰县| 卫辉市| 安义县| 焦作市| 丽水市| 海宁市| 平遥县| 乌恰县| 都江堰市| 来凤县| 绥芬河市| 河北省| 百色市| 天镇县| 天全县| 土默特右旗| 商洛市| 平和县| 道孚县| 宝坻区| 邹平县| 安顺市| 台南市| 营口市| 都昌县| 资中县| 广河县| 泽州县| 兰坪| 台中市| 宁强县| 巧家县| 隆安县| 蓬溪县|