GBase 8s 检查是否是IP且转数值函数

GBase 8s中没有ip类型字段(如inet),对于判断字符串是否是IP地址,需要自己编写相应的函数。
如下,实现检查输入的字符串是否为IPv4地址(-1否),且转换成数值类型:

-- function ip to num, if not ip return -1
DROP FUNCTION IF EXISTS func_ip2num(varchar);
CREATE FUNCTION func_ip2num(p_ip varchar(20))
RETURNS int8 WITH (NOT VARIANT);
  define v_ip1 varchar(10);
  define v_ip2 varchar(10);
  define v_ip3 varchar(10);
  define v_ip4 varchar(10);
  define v_ipnum int8;
  define v_delpos smallint;
  define v_curpos smallint;
  ON EXCEPTION
    RETURN -1;
  END EXCEPTION;

  let v_ipnum = -1;
  -- ip part1
  let v_delpos = charindex('.',p_ip);
  let v_ip1 = substr(p_ip,1,v_delpos - 1)::int;
  -- ip part2
  let v_curpos = v_delpos + 1;
  let v_delpos = charindex('.',p_ip,v_curpos);
  let v_ip2 = substr(p_ip,v_curpos,v_delpos - v_curpos)::int;
  -- ip part3
  let v_curpos = v_delpos + 1;
  let v_delpos = charindex('.',p_ip,v_curpos);
  let v_ip3 = substr(p_ip,v_curpos,v_delpos - v_curpos)::int; 
  -- ip part4
  let v_curpos = v_delpos + 1;
  let v_ip4 = substr(p_ip,v_curpos)::int;
  IF v_ip1 < 0 OR v_ip2 < 0 OR v_ip3 < 0 OR v_ip4 < 0 OR
     v_ip1 > 255 OR v_ip2 > 255 OR v_ip3 > 255 OR v_ip4 > 255 THEN
    RETURN -1;
  END IF;
  let v_ipnum = v_ip1 * 16777216 + v_ip2 * 65536 + v_ip3 * 256 + v_ip4;
  
  RETURN v_ipnum;
END FUNCTION;

示例:

SELECT func_ip2num('192.168.100.100') FROM dual;  -- 返回:3232261220

SELECT func_ip2num('192.-168.100.100') FROM dual;  -- 返回 -1,不是IP

SELECT func_ip2num('292.-168.100.100') FROM dual;  -- 返回 -1,不是IP

注:当然仅仅需要判断是否为IP,也可以使用regexp_like功能:

SELECT regexp_like('192.168.100.100', '^(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$') FROM dual;

标签: GBase, IP转数值, 判断IP

添加新评论