SQL function to convert an integer into an IP address. Note: 255 could be replaced with X'FF'::integer if that makes more sense to you. CREATE OR REPLACE FUNCTION long_to_ip ( integer ) RETURNS text AS ' SELECT (($1 >> 24) & 255)::text || \'.\' || (($1 >> 16) & 255)::text || \'.\' || (($1 >> 8) & 255)::text || \'.\' || ($1 & 255)::text; ' LANGUAGE SQL IMMUTABLE RETURNS NULL ON NULL INPUT; --------------------------------------------------------------------------- Here's a convenience C function to convert from IPs to integers. See the PostgreSQL docs for directions for compiling for your specific platform. #include "postgres.h" #include "fmgr.h" #include #include PG_FUNCTION_INFO_V1(ip_to_long); Datum ip_to_long(PG_FUNCTION_ARGS) { text* text_ip_in = PG_GETARG_TEXT_P(0); int32 longIP = 0; int octets[4] = {0, 0, 0, 0}; char textIP[16] = {0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0}; char* ipAddress = textIP; char* dot; int octetIdx; /* put input text into textIP char array */ memcpy( (void*) textIP, (void*) VARDATA(text_ip_in), 15 ); /* put each class into octets array */ for( octetIdx = 0; octetIdx < 4; octetIdx++ ) { dot = strchr( ipAddress, '.' ); if (dot) { *dot = '\0'; octets[octetIdx] = atoi(ipAddress); ipAddress = dot + 1; } else { /* dot not found, must be last octet */ octets[octetIdx] = atoi(ipAddress); break; } } /* put octets into long IP */ longIP = (octets[0] & 0xFF) << 24 | (octets[1] & 0xFF) << 16 | (octets[2] & 0xFF) << 8 | (octets[3] & 0xFF); PG_RETURN_INT32(longIP); } Once compiled, put the library in the correct place and create a PostgreSQL function like this. Note that you must be logged in as superuser to create the function. CREATE OR REPLACE FUNCTION ip_to_long ( text ) RETURNS integer AS '$libdir/ip_to_long' LANGUAGE C IMMUTABLE RETURNS NULL ON NULL INPUT;