I think you need to define what you're trying to achieve better. Do you just want to know if anything is listening on a certain point? If PostgreSQL is listening on a given port? If PostgreSQL is running and actually accepting connections? If you can connect to PostgreSQL, authenticate successfully and issue queries?
One option is to invoke psql
to connect to it and check the result code. Do not attempt to parse the output text, since that's subject to translation into different languages.
Better, use the client library for the language of your choice - psycopg2
for Python, PgJDBC for Java, the Pg gem for Ruby, DBD::Pg
for Perl, nPgSQL for C#, etc. This is the approach I'd recommend. The SQLSTATE or exception details from any connection error will tell you more about why the connection failed - you'll be able to tell the difference between the server not listening, authentication failure, etc this way. For example, in Python:
import psycopg2
try:
conn = psycopg2.connect("host=localhost dbname=postgres")
conn.close()
except psycopg2.OperationalError as ex:
print("Connection failed: {0}".format(ex))
There are exception details in ex.pgcode
(the SQLSTATE
) to tell you more about errors that're generated server-side, like authentication failures; it'll be empty for client-side errors.
If you just want to see if something is listening on a given IP and TCP port, you can use netcat
(*nix only), or a simple script in the language of your choice that creates a socket and does a connect() then closes the socket if it gets a successful response. For example, the following trivial Python script:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect(('localhost',5432))
s.close()
except socket.error as ex:
print("Connection failed with errno {0}: {1}".format(ex.errno, ex.strerror))
The same approach applies in any programming language, just the details of the socket library and error handling vary.
For some purposes it can also be useful to use the netstat
tool to passively list which processes are listening on which network sockets. The built-in netstat
on Windows is pretty brain-dead so you have to do more parsing of the output than with netstat
for other platforms, but it'll still do the job. The presence of a socket in netstat
doesn't mean that connecting to it will succeed, though; if the process has failed in some way that leaves it broken but still running (stuck in an infinite loop, blocked by a debugger, SIGSTOP
ed, etc) then it won't respond to an actual connection attempt.
curl -v -sL -I localhost:5432/ping
taken from github.com/influxdata/influxdb/issues/4595 – Belostok