From add6d724e304158f289021ac8398323ed2841536 Mon Sep 17 00:00:00 2001 From: Joris Vink Date: Fri, 24 Mar 2017 12:42:40 +0100 Subject: [PATCH] expose connection address to python. --- includes/python_methods.h | 2 ++ src/python.c | 30 ++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/includes/python_methods.h b/includes/python_methods.h index 1d3668f..c629ec4 100644 --- a/includes/python_methods.h +++ b/includes/python_methods.h @@ -59,9 +59,11 @@ static PyMethodDef pyconnection_methods[] = { }; static PyObject *pyconnection_get_fd(struct pyconnection *, void *); +static PyObject *pyconnection_get_addr(struct pyconnection *, void *); static PyGetSetDef pyconnection_getset[] = { GETTER("fd", pyconnection_get_fd), + GETTER("addr", pyconnection_get_addr), GETTER(NULL, NULL), }; diff --git a/src/python.c b/src/python.c index 750651b..9d7083c 100644 --- a/src/python.c +++ b/src/python.c @@ -696,6 +696,36 @@ pyconnection_get_fd(struct pyconnection *pyc, void *closure) return (fd); } +static PyObject * +pyconnection_get_addr(struct pyconnection *pyc, void *closure) +{ + void *ptr; + PyObject *result; + char addr[INET6_ADDRSTRLEN]; + + switch (pyc->c->addrtype) { + case AF_INET: + ptr = &pyc->c->addr.ipv4.sin_addr; + break; + case AF_INET6: + ptr = &pyc->c->addr.ipv6.sin6_addr; + break; + default: + PyErr_SetString(PyExc_RuntimeError, "invalid addrtype"); + return (NULL); + } + + if (inet_ntop(pyc->c->addrtype, ptr, addr, sizeof(addr)) == NULL) { + PyErr_SetString(PyExc_RuntimeError, "inet_ntop failed"); + return (NULL); + } + + if ((result = PyUnicode_FromString(addr)) == NULL) + return (PyErr_NoMemory()); + + return (result); +} + static PyObject * pyhttp_request_alloc(struct http_request *req) {