How to create a socket.socket() object from a socket fd?

Grant Edwards grant.b.edwards at gmail.com
Sat Jan 21 19:03:37 EST 2017


On 2017-01-21, Christian Heimes <christian at python.org> wrote:

> You might be interested in my small module
> https://pypi.python.org/pypi/socketfromfd/ . I just releases a new
> version with a fix for Python 2. Thanks for the hint! :)
>
> The module correctly detects address family, socket type and proto from
> a fd. It works correctly with e.g. IPv6 or Unix sockets. Ticket
> https://bugs.python.org/issue28134 has additional background information
> on the matter.

Yes, thanks!

Just a few minutes ago I stumbled across that issue.  For Python3, I
was using:

  sock = socket.socket(fileno=fd)

But as you point out in that issue, the Python3 docs are wrong: when
using socket.socket(fileno=fd) you _do_ have to specify the correct
family and type parameters that correspond to the socket file
descriptor. So, I starting looking for os.getsockopt(), which doesn't
exist.

I see you use ctypes to call gestsockopt (that was going to be my next
step).

I suspect the code I'm working will end up being re-written in C for
the real product (so that it can run in-process in a thread rather
than as an external helper process).  If not, I'll have to use your
module (or something like it) so that the solution will work on both
IPv4 and IPv6 TCP sockets (I'd also like it to work with Unix domain
sockets, but the piece at the other end of the socket connection
currently only supports TCP).

-- 
Grant







More information about the Python-list mailing list