Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert IP address in PostgreSQL to integer?

Tags:

postgresql

ip

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?

like image 653
user2315 Avatar asked Mar 27 '13 15:03

user2315


People also ask

How do I convert text to integer in PostgreSQL?

The PostgreSQL TO_NUMBER() function converts a character string to a numeric value.

How do you check IP address in Postgres?

select inet_client_addr(); gives you the client IP, not server, next postgres has no tools for host resolve... If you are using DB computer (1) + server computer (2) + client's computer (3) and need an ip of client (3), you have to resolve it on the server (2), since (1) does not has direct connection with (3).

What is the difference between int and Integer in PostgreSQL?

Integer. There are three kinds of integers in PostgreSQL: Small integer ( SMALLINT ) is 2-byte signed integer that has a range from -32,768 to 32,767. Integer ( INT ) is a 4-byte integer that has a range from -2,147,483,648 to 2,147,483,647.


3 Answers

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

like image 71
AlexM Avatar answered Oct 11 '22 21:10

AlexM


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.

like image 32
leonbloy Avatar answered Oct 11 '22 21:10

leonbloy


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
like image 32
mad Avatar answered Oct 11 '22 21:10

mad