From 555e9f4489d0707d642959247e2c005d89a8d685 Mon Sep 17 00:00:00 2001 From: Emanuele Giaquinta Date: Mon, 11 Mar 2024 12:38:35 +0200 Subject: [PATCH] Add connection.get_host_addr() --- doc/src/connection.rst | 14 ++++++++++++++ psycopg/connection_type.c | 12 ++++++++++++ tests/test_connection.py | 3 +++ 3 files changed, 29 insertions(+) diff --git a/doc/src/connection.rst b/doc/src/connection.rst index 05ad1404..6d29ce02 100644 --- a/doc/src/connection.rst +++ b/doc/src/connection.rst @@ -910,6 +910,20 @@ The ``connection`` class .. versionadded:: 2.7 + .. index:: + pair: Connection; Parameters + + .. method:: get_host_addr() + + Get the server IP address of the active connection. + + .. seealso:: libpq docs for `PQhostaddr()`__ for details. + + .. __: https://www.postgresql.org/docs/current/libpq-status.html#LIBPQ-PQHOSTADDR + + .. versionadded:: 2.9.10 + + .. testcode:: :hide: diff --git a/psycopg/connection_type.c b/psycopg/connection_type.c index 339f7f18..6073316f 100644 --- a/psycopg/connection_type.c +++ b/psycopg/connection_type.c @@ -947,6 +947,16 @@ exit: #endif } +#define psyco_conn_get_host_addr_doc \ +"get_host_addr() -- Get the server IP address of the active connection." + +static PyObject * +psyco_conn_get_host_addr(connectionObject *self, PyObject *dummy) +{ + EXC_IF_CONN_CLOSED(self); + + return Text_FromUTF8(PQhostaddr(self->pgconn)); +} /* lobject method - allocate a new lobject */ @@ -1220,6 +1230,8 @@ static struct PyMethodDef connectionObject_methods[] = { METH_VARARGS, psyco_conn_get_parameter_status_doc}, {"get_dsn_parameters", (PyCFunction)psyco_conn_get_dsn_parameters, METH_NOARGS, psyco_conn_get_dsn_parameters_doc}, + {"get_host_addr", (PyCFunction)psyco_conn_get_host_addr, + METH_NOARGS, psyco_conn_get_host_addr_doc}, {"get_backend_pid", (PyCFunction)psyco_conn_get_backend_pid, METH_NOARGS, psyco_conn_get_backend_pid_doc}, {"lobject", (PyCFunction)psyco_conn_lobject, diff --git a/tests/test_connection.py b/tests/test_connection.py index 728176c2..ad0b9cc9 100755 --- a/tests/test_connection.py +++ b/tests/test_connection.py @@ -1826,6 +1826,9 @@ class TestConnectionInfo(ConnectingTestCase): self.assertEqual(d['dbname'], dbname) # the only param we can check reliably self.assert_('password' not in d, d) + def test_host_addr(self): + self.assertEqual(self.conn.get_host_addr(), "") + def test_status(self): self.assertEqual(self.conn.info.status, 0) self.assertEqual(self.bconn.info.status, 1)