Pg gethostname

From PostgreSQL wiki

Revision as of 09:03, 25 February 2013 by Yin_yang2k (Talk | contribs)

Jump to: navigation, search

Library Snippets

C function to get server hostname

Works with PostgreSQL

9.0+

Written in

C

Depends on

Nothing


Here is a compilable C function to get the server hostname.

Tested with CentOS 5 x86_64, postgresql 9.0 & 9.1.

Probably works in earlier versions of pg and other linux distros, but haven't tested.

/*
	A PostgreSQL function for getting the hostname.
 
        File: `pg_config --libdir`/pg_gethostname.c
 
	To compile...  (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 funciton in PostgreSQL...
	CREATE OR REPLACE FUNCTION pg_gethostname() RETURNS text
		AS 'pg_gethostname'
		LANGUAGE C IMMUTABLE STRICT;
 
*/
#include "postgres.h"
#include <limits.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
 
 
PG_FUNCTION_INFO_V1( pg_gethostname );
 
Datum pg_gethostname( PG_FUNCTION_ARGS );
 
Datum pg_gethostname( PG_FUNCTION_ARGS )
{
	text *t;
	char server_hostname[HOST_NAME_MAX];
	size_t length;
 
	if ( gethostname( server_hostname, HOST_NAME_MAX ) != 0 )
	{
		// returning an empty string for the hostname if it fails makes
		// sense because if it succeeded, we would have a name
		server_hostname[0] = '\0';
	}
 
	length = strnlen( server_hostname, HOST_NAME_MAX );
	t = (text *) palloc(VARHDRSZ + length );
	SET_VARSIZE( t, VARHDRSZ + length );
	memcpy( VARDATA(t), server_hostname, length );
 
	PG_RETURN_TEXT_P( t );
}

Usage:

postgres# select pg_gethostname();
 pg_gethostname 
----------------
 myserver


Installation with a makefile

http://www.postgresql.org/docs/9.1/static/extend-pgxs.html

This worked for me on Ubuntu 12.04 64bit PostgreSQL 9.1

Create a makefile in the directory of your choice

# makefile
MODULES = pg_gethostname

PG_CONFIG = pg_config
PGXS := $(shell $(PG_CONFIG) --pgxs)
include $(PGXS)

Put pg_gethostname.c in the same directory and run the following script. You have to have pg_config in your path

#!/bin/bash
# Install script
PGXS=`pg_config --pgxs`
PG_CONFIG=`which pg_config`
make
make install
echo "CREATE OR REPLACE FUNCTION pg_gethostname() RETURNS text AS 'pg_gethostname' LANGUAGE C IMMUTABLE STRICT;" | psql -U postgres template1
Personal tools