Convert IP address in PostgreSQL to integer?

喜夏-厌秋 提交于 2021-01-02 05:58:27

问题


Is there a query that would be able to accomplish this?

For example given an entry '216.55.82.34' ..I would want to split the string by the '.'s, and apply the equation:

IP Number = 16777216*w + 65536*x + 256*y + z where IP Address = w.x.y.z

Would this be possible from just a Query?


回答1:


You can use split_part(). For example:

CREATE FUNCTION ip2int(text) RETURNS bigint AS $$ 
SELECT split_part($1,'.',1)::bigint*16777216 + split_part($1,'.',2)::bigint*65536 +
 split_part($1,'.',3)::bigint*256 + split_part($1,'.',4)::bigint;
$$ LANGUAGE SQL  IMMUTABLE RETURNS NULL ON NULL INPUT;


SELECT ip2int('200.233.1.2');
>> 3370713346

Or, if don't want to define a function, simply :

SELECT split_part(ip,'.',1)::bigint*16777216 + split_part(ip,'.',2)::bigint*65536 +
 split_part(ip,'.',3)::bigint*256 + split_part(ip,'.',4)::bigint;

The drawback of the later is that, if the value is given by some computation instead of being just a table field, it can be inefficient to compute, or ugly to write.




回答2:


You can simply convert inet data-type to bigint: (inet_column - '0.0.0.0'::inet)

For example:

SELECT ('127.0.0.1'::inet - '0.0.0.0'::inet) as ip_integer

will output 2130706433, which is the integer representation of IP address 127.0.0.1




回答3:


PG 9.4

create or replace function ip2numeric(ip varchar) returns numeric AS
$$
DECLARE
  ip_numeric numeric;
BEGIN
  EXECUTE format('SELECT inet %L - %L', ip, '0.0.0.0') into ip_numeric;

  return ip_numeric;
END;
$$ LANGUAGE plpgsql;

Usage

select ip2numeric('192.168.1.2');
$ 3232235778



回答4:


create function dbo.fn_ipv4_to_int( p_ip text)
returns int
as $func$ 
select cast(case when cast( split_part(p_ip, '.', 1 ) as int ) >= 128
then 
(
( 256 - cast(split_part(p_ip, '.', 1 ) as int ))
* 
-power ( 2, 24 ) 
)
+ (cast( split_part(p_ip, '.', 2 ) as int ) * 65536 )
+ (cast( split_part(p_ip, '.', 3 ) as int ) * 256 )
+ (cast( split_part(p_ip, '.', 4 ) as int )  )

else (cast(split_part(p_ip, '.', 1 ) as int) * 16777216)
+ (cast(split_part(p_ip, '.', 2 ) as int) * 65536)
+ (cast(split_part(p_ip, '.', 3 ) as int) * 256)
+ (cast(split_part(p_ip, '.', 4 ) as int))
end as int )
$func$ LANGUAGE SQL  IMMUTABLE RETURNS NULL ON NULL INPUT;

in case you need to get a 32 bit int. it'll return negative numbers for ips over 128.0.0.0. I'd use bigint if you can, but i had a case when i had the numbers stored as 32 bit numbers from another database.



来源:https://stackoverflow.com/questions/15662805/convert-ip-address-in-postgresql-to-integer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!