I had a need recently to get the server hostname of some databases that we were unit-testing and couldn't find a built-in function for it. One of my coworkers put together a C function that seems to work well. Does anyone have any suggestions or improvements to the code below? Some testing was done with both 9.0 and and 9.1, linux, x86_64 To use: select pg_gethostname(); /* A PostgreSQL function for getting the hostname. File: `pg_config --libdir`/pg_gethostname.c To compile: //gcc -fpic -c pg_gethostname.c //gcc -shared -o pg_gethostname.so pg_gethostname.o Note: the compile options above did work, amended steps: // make sure pg_config is in your path gcc -I`pg_config --includedir-server` -fpic -c pg_gethostname.c -L`pg_config --libdir` gcc -shared -o pg_gethostname.so pg_gethostname.o To create the function in PostgreSQL. //DROP FUNCTION IF EXISTS pg_gethostname(); CREATE OR REPLACE FUNCTION pg_gethostname() RETURNS text AS 'pg_gethostname' LANGUAGE C IMMUTABLE STRICT; */ #include "postgres.h" #include <unistd.h> #include <string.h> #include "fmgr.h" #include "utils/palloc.h" #include "utils/elog.h" #include "storage/bufpage.h" #ifdef PG_MODULE_MAGIC PG_MODULE_MAGIC; #endif #define MAX_HOSTNAME_LENGTH 255 PG_FUNCTION_INFO_V1( pg_gethostname ); Datum pg_gethostname( PG_FUNCTION_ARGS ); Datum pg_gethostname( PG_FUNCTION_ARGS ) { text *t; char server_hostname[MAX_HOSTNAME_LENGTH]; size_t length; if ( gethostname( server_hostname, MAX_HOSTNAME_LENGTH ) != 0 ) { // things are not okay strncpy( server_hostname, "UNKNOWN", MAX_HOSTNAME_LENGTH ); } length = strnlen( server_hostname, MAX_HOSTNAME_LENGTH ); t = (text *) palloc(VARHDRSZ + length ); SET_VARSIZE( t, VARHDRSZ + length ); memcpy( VARDATA(t), server_hostname, length ); PG_RETURN_TEXT_P( t ); } -- Sent via pgsql-general mailing list (pgsql-general@xxxxxxxxxxxxxx) To make changes to your subscription: http://www.postgresql.org/mailpref/pgsql-general