Example of a pg_gethostname() function. Feedback?

From: bricklen <bricklen(at)gmail(dot)com>
To: pgsql-general(at)postgresql(dot)org
Subject: Example of a pg_gethostname() function. Feedback?
Date: 2011-12-23 18:47:14
Message-ID: CAGrpgQ_bXy8bb_ztFsL76CV6-fyZXDu5Yk_U+i5ku8qSVM0O8g@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

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 );
}

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Ben Chobot 2011-12-24 01:47:37 Re: Initdb fails on openwrt in "creating template1 database"
Previous Message Peter Eisentraut 2011-12-23 17:48:21 Re: How to create database with default system locale is set to et_EE.UTF-8