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

Christian Heimes christian at python.org
Sun Jan 22 06:48:31 EST 2017


On 2017-01-22 01:03, Grant Edwards wrote:
> 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).

I wanted to fix the function before 3.6.0 came out but I faced some
resistance. My approach was deemed too magic and not fully functional on
some platforms. Other core devs are underestimating the severity of the
issue. Even in simple examples with IPv4 and IPv6 it breaks
getpeername(). I'd appreciate if you could jump in a leave a comment on
the ticket to show your support. :)

By the way I just pushed another commit with a new feature just for you.
But see for yourself:

https://github.com/tiran/socketfromfd/commit/0a2fd6dae86267cedea5ae8b956e2876e6057c74

Christian


More information about the Python-list mailing list