How to add inet_aton() and inet_ntoa() to PostgreSQL?

March 10th, 2006 in Linux, Programming, SQL

CREATE OR REPLACE FUNCTION inet_aton(text) RETURNS bigint AS '
SELECT
split_part($1,''.'',1)::int8*(256*256*256)+
split_part($1,''.'',2)::int8*(256*256)+
split_part($1,''.'',3)::int8*256+
split_part($1,''.'',4)::int8;
' LANGUAGE 'SQL';

CREATE OR REPLACE FUNCTION inet_ntoa(bigint) RETURNS text AS '
SELECT (($1>>24) & 255::int8) || ''.'' ||
(($1>>16) & 255::int8) || ''.'' ||
(($1>>8) & 255::int8) || ''.'' ||
($1 & 255::int8) as result
'
LANGUAGE 'SQL';
Examples:

SELECT INET_ATON('127.0.0.1');
inet_aton
————
2130706433
(1 row)

SELECT INET_NTOA(2130706433);
inet_ntoa
———–
127.0.0.1
(1 row)
Warning!

INET_ATON() does NOT understand short-form IP addresses!

SELECT INET_ATON('127.1'); will NOT work!

Leave a Reply

You must be logged in to post a comment.