--- /dev/null
+#include <ident.h>
+
+#include <postgres.h>
+#include <miscadmin.h>
+#include <libpq/libpq-be.h>
+#include <fmgr.h>
+
+char *ident_result = NULL;
+
+PG_FUNCTION_INFO_V1(get_ident);
+Datum get_ident(PG_FUNCTION_ARGS) {
+ IDENT *id;
+
+ if (MyProcPort == NULL)
+ elog(ERROR, "could not get ident for user: no port");
+
+ if (!ident_result) {
+ id = ident_lookup(MyProcPort->sock, 5);
+ if (id && id->identifier) ident_result = strdup(id->identifier);
+ }
+
+ if (ident_result) {
+ int len;
+ VarChar* result;
+
+ len = strlen(ident_result);
+ if (len > 8) len = 8;
+ result = palloc(len + VARHDRSZ);
+ VARATT_SIZEP(result) = len + VARHDRSZ;
+ memcpy(VARDATA(result), ident_result, len);
+
+ PG_RETURN_VARCHAR_P(result);
+ }
+
+ elog(ERROR, "could not get ident for user: ident failed");
+
+ /* not reached */
+ PG_RETURN_NULL();
+}