Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions Doc/library/socket.rst
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,22 @@ The following functions all create :ref:`socket objects <socket-objects>`.
The returned socket is now non-inheritable.


.. function:: fromfd2(fd)

Create a socket object from the file descriptor *fd* (as returned
by a file object's :meth:`fileno` method). The file descriptor
is not duplicated. If the file descriptor is not a socket,
:exc:`OSError` is raised. The family and type of the socket is
determined from the file descriptor. If possible, the protocol
is also determined. On some platforms, determining the protocol is
not possible and :attr:`socket.proto` is set to zero. The socket
is assumed to be in blocking mode.

Availability: Unix.

.. versionadded:: 3.6


.. function:: fromshare(data)

Instantiate a socket from data obtained from the :meth:`socket.share`
Expand Down Expand Up @@ -874,6 +890,24 @@ The :mod:`socket` module also offers various network-related services:
.. versionadded:: 3.3


.. function:: fdtype(fd)

Get socket information from a file descriptor. The return value
is a 3-tuple with the following structure:

``(family, type, proto)``

The values of *family*, *type*, *proto* are all integers and are
meant to be passed to the :func:`.socket` function. If the file
descriptor is not a socket, :exc:`OSError` is raised. On some
platforms, determining the protocol is not possible and in those
cases it is returned as zero.

Availability: Unix

.. versionadded:: 3.6


.. _socket-objects:

Socket Objects
Expand Down
26 changes: 26 additions & 0 deletions Lib/socket.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
socket() -- create a new socket object
socketpair() -- create a pair of new socket objects [*]
fromfd() -- create a socket object from an open file descriptor [*]
fromfd2() -- create a socket object without duplicating a file descriptor [*]
fromshare() -- create a socket object from data received from socket.share() [*]
gethostname() -- return the current hostname
gethostbyname() -- map a hostname to its IP number
Expand All @@ -24,6 +25,7 @@
inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89)
socket.getdefaulttimeout() -- get the default timeout value
socket.setdefaulttimeout() -- set the default timeout value
fdtype() -- get (family, type, protocol) from a socket file descriptor [*]
create_connection() -- connects to an address, with an optional timeout and
optional source address.

Expand Down Expand Up @@ -460,6 +462,30 @@ def fromfd(fd, family, type, proto=0):
nfd = dup(fd)
return socket(family, type, proto, nfd)

if hasattr(_socket, 'fdtype'):
def fdtype(fd):
"""fdtype(fd) -> (family, type, proto)

Return (family, type, proto) for a socket given a file descriptor.
Raises OSError if the file descriptor is not a socket.
"""
family, type, proto = _socket.fdtype(fd)
return (_intenum_converter(family, AddressFamily),
_intenum_converter(type, SocketKind),
proto)

def fromfd2(fd):
"""fromfd2(fd) -> socket object

Create a socket object from the given file descriptor. Unlike fromfd,
the descriptor is not duplicated. The family, type and protocol of
the socket is determined using fdtype(). Raises OSError if the file
descriptor is not a socket.
"""
family, type, proto = _socket.fdtype(fd)
return socket(family, type, proto, fd)
__all__.append('fromfd2')

if hasattr(_socket.socket, "share"):
def fromshare(info):
""" fromshare(info) -> socket object
Expand Down
56 changes: 55 additions & 1 deletion Lib/test/test_socket.py
Original file line number Diff line number Diff line change
Expand Up @@ -5047,6 +5047,59 @@ def test_SOCK_NONBLOCK(self):
socket.setdefaulttimeout(t)


@unittest.skipUnless(hasattr(socket, "fdtype"),
"socket.fdtype() not defined")
class FdTypeTests(unittest.TestCase):
TYPES = [
(socket.AF_INET, socket.SOCK_STREAM, 0),
(socket.AF_INET, socket.SOCK_DGRAM, 0),
]
_add = TYPES.append
if hasattr(socket, 'IPPROTO_TCP'):
_add((socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP))
if hasattr(socket, 'AF_UNIX'):
_add((socket.AF_UNIX, socket.SOCK_STREAM, 0))
_add((socket.AF_UNIX, socket.SOCK_DGRAM, 0))
if HAVE_SOCKET_CAN:
_add((socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW))
# This fails, not sure if Linux bug?
#if hasattr(socket, 'CAN_BCM'):
# _add((socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_BCM))
if hasattr(socket, 'IPPROTO_SCTP'):
_add((socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_SCTP))
if HAVE_SOCKET_RDS:
_add((socket.PF_RDS, socket.SOCK_SEQPACKET, 0))

def test_fdtype(self):
for family, kind, proto in self.TYPES:
s = socket.socket(family, kind, proto)
with s:
family2, kind2, proto2 = socket.fdtype(s.fileno())
self.assertEqual(family, family2)
self.assertEqual(kind, kind2)
# depending on platform, we may not be able to find proto,
# the returned value could be zero or the actual protocol
# used for the socket
if proto != 0:
self.assertIn(proto2, {proto, 0})

def test_fromfd2(self):
for family, kind, proto in self.TYPES:
s = socket.socket(family, kind, proto)
with s:
s2 = socket.fromfd2(s.fileno())
try:
self.assertEqual(s.family, s2.family)
self.assertEqual(s.type, s2.type)
if proto != 0:
self.assertIn(s.proto, {proto, 0})
self.assertEqual(s.fileno(), s2.fileno())
finally:
s2.detach()
with tempfile.TemporaryFile() as tmp:
self.assertRaises(OSError, socket.fromfd2, tmp.fileno())
self.assertRaises(OSError, socket.fromfd2, -1)

@unittest.skipUnless(os.name == "nt", "Windows specific")
@unittest.skipUnless(multiprocessing, "need multiprocessing")
class TestSocketSharing(SocketTCPTest):
Expand Down Expand Up @@ -5613,7 +5666,8 @@ def test_main():
NetworkConnectionBehaviourTest,
ContextManagersTest,
InheritanceTest,
NonblockConstantTest
NonblockConstantTest,
FdTypeTests,
])
tests.append(BasicSocketPairTest)
tests.append(TestUnixDomain)
Expand Down
68 changes: 66 additions & 2 deletions Modules/socketmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -5470,6 +5470,60 @@ AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
#endif /* HAVE_SOCKETPAIR */


/* socket.fdtype() function */

#ifndef MS_WINDOWS
/* set if we can implement fdtype(). On Windows, getsockname() fails with
error 10022. There may be other platforms that have SO_TYPE but also
don't provide the necessary functionality. */
#define HAVE_FDTYPE
#endif

#ifdef HAVE_FDTYPE
static PyObject *
socket_fdtype(PyObject *self, PyObject *fdobj)
{
SOCKET_T fd;
int sock_type;
struct sockaddr sa;
socklen_t l;
int protocol;

fd = PyLong_AsSocket_t(fdobj);
if (fd == (SOCKET_T)(-1) && PyErr_Occurred())
return NULL;

l = sizeof(sock_type);
if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &sock_type, &l) < 0) {
return set_error();
}

l = sizeof(sa);
if (getsockname(fd, &sa, &l) < 0) {
return set_error();
}
#ifdef SO_PROTOCOL
l = sizeof(protocol);
if (getsockopt(fd, SOL_SOCKET, SO_PROTOCOL, &protocol, &l) < 0) {
return set_error();
}
#else
protocol = 0;
#endif
return Py_BuildValue("iii",
sa.sa_family,
sock_type,
protocol);
}

PyDoc_STRVAR(fdtype_doc,
"fdtype(integer) -> (family, type, protocol)\n\
\n\
Return the family, type and protocol for socket given a file descriptor.\
");
#endif /* HAVE_FDTYPE */


static PyObject *
socket_ntohs(PyObject *self, PyObject *args)
{
Expand Down Expand Up @@ -6381,6 +6435,10 @@ static PyMethodDef socket_methods[] = {
#ifdef HAVE_SOCKETPAIR
{"socketpair", socket_socketpair,
METH_VARARGS, socketpair_doc},
#endif
#ifdef HAVE_FDTYPE
{"fdtype", socket_fdtype,
METH_O, fdtype_doc},
#endif
{"ntohs", socket_ntohs,
METH_VARARGS, ntohs_doc},
Expand Down Expand Up @@ -6967,12 +7025,18 @@ PyInit__socket(void)
#ifdef SO_MARK
PyModule_AddIntMacro(m, SO_MARK);
#endif
#ifdef SO_DOMAIN
#ifdef SO_DOMAIN
PyModule_AddIntMacro(m, SO_DOMAIN);
#endif
#ifdef SO_PROTOCOL
#ifdef SO_PROTOCOL
PyModule_AddIntMacro(m, SO_PROTOCOL);
#endif
#ifdef SO_PEERSEC
PyModule_AddIntMacro(m, SO_PEERSEC);
#endif
#ifdef SO_PASSSEC
PyModule_AddIntMacro(m, SO_PASSSEC);
#endif

/* Maximum number of connections for "listen" */
#ifdef SOMAXCONN
Expand Down