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

Chris Angelico rosuav at gmail.com
Sat Jan 21 17:39:41 EST 2017


On Sun, Jan 22, 2017 at 9:28 AM, Grant Edwards
<grant.b.edwards at gmail.com> wrote:
> Given a Unix file discriptor for an open TCP socket, I can't figure
> out how to create a python 2.7 socket object like those returned by
> socket.socket()

I suspect you can't easily do it. In more recent Pythons, you can
socket.socket(fileno=N), but that doesn't exist in 2.7. But maybe.....

> Here's what a "socket object" returned by socket.socket() looks like:
>
>   repr(osock):
>   <socket._socketobject object at 0x7f701948f520>
>
> Here's what a "socket object" returned from socket.fromfd() object looks like:
>
>   repr(sock):
>   <socket object, fd=6, family=2, type=1, protocol=0>
>
> Note that the socket.socket() object has a '_sock' attribute, which
> appears to contain an object like that returned by socket.fromfd():
>
>   repr(osock._sock):
>   <socket object, fd=4, family=2, type=1, protocol=0>

... maybe you could construct a socket.socket(), then monkeypatch its _sock??

> [An ssl context will wrap the latter, but not the former, in case
> you're wondering why I care about the difference.]
>
> Also, I passed socket.fromfd fd==5, and the resulting "socket object"
> is using fd==6. Why does socket.fromfd() duplicate the fd?  If I
> wanted the file descriptor duplicated, I would have do it myself!
> [Yes, I know the documentation _says_ it will duplicate the fd, I just
> don't understand why, and I think it a bad idea.]

Agreed. It's much cleaner in Py3, but I don't know of a backport.

ChrisA



More information about the Python-list mailing list