Can I use the hostname of the server in a PostgreSQL SELECT statement? The following may be close but apparently does not quite work:

\set x \! hostname
select :x;

This is for PostgreSQL 9.6 on Debian.


I don't think it's possible. I think what you're looking for is gethostname(). That's not called anywhere in the PostgreSQL source code. Nor is utsname or any kernel interface into this.

What is called is getaddrinfo that provides a CANONNAME but that's essentially just your own method of addressing the server not the "symbolic hostname". If you need the hostname, you'll have to build a C-extension that does just that. Or, use a third party procedural language, like perl plperlu, that has that support (through Sys::Hostname or Net::Domain, see perldoc -q hostname); or, alternatively through javascript with plv8 that has os.hostname().

Another method would be simply reading the file /proc/sys/kernel/hostname.

It's a database, not a remote administration utility. You can't really fault it for not doing this.

  • 1
    So you suggest there is now way to "pipe" the output from \! hostname (when executed from inside PostgreSQL) into an SQL statement?
    – rookie09
    Dec 1 '17 at 9:21
  • 1
    @rookie09 do you want the hostname of the client, or the server? The server doesn't provide shell access to the client, through the client. When you do \! you're accessing the shell of the client, not the server. Dec 8 '17 at 21:48
  • Extellent point, thx.
    – rookie09
    Dec 13 '17 at 9:15

PostgreSQL has 2 functions for getting server address information. inet_server_addr() and inet_server_port() which provide ip address and port information of the server.

However I don't know a direct way for getting hostname. So, you may try this;

You can use postgresql.conf to create a custom configuration and use current_setting function to get that value. Here is detailed description.

For other system functions you can check System Information Functions section of the documentation.

  • 1
    I need the (symbolic) hostname, not the (numeric) IP address of the server.
    – rookie09
    Nov 30 '17 at 14:31
  • if its not dynamic then use custom setting option
    – Sahap Asci
    Dec 2 '17 at 12:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.