Python Glossary Русский

Python 3.3+Linux · macOSsocketfunction

socket.CMSG_SPACE()

file descriptors and ancillary data

Returns the recvmsg buffer size needed for an ancillary data item of the given length, including padding.

Syntax

socket.CMSG_SPACE(length) -> int

This is the right measure for the second argument of recvmsg: N descriptors need CMSG_SPACE(N * int_size), and several items need the sum of their CMSG_SPACE values. A buffer that is too small raises no error: ancillary data is silently truncated, MSG_CTRUNC is set and extra descriptors vanish. It is not available on every Unix system.

Examples

import array, os, socket
a, b = socket.socketpair()
r, w = os.pipe()
fds = array.array('i', [w])
a.sendmsg([b'x'], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, fds)])
msg, anc, flags, addr = b.recvmsg(1, socket.CMSG_SPACE(fds.itemsize))
level, kind, data = anc[0]
got = array.array('i')
got.frombytes(data[:fds.itemsize])
os.write(got[0], b'hi')
print(os.read(r, 2))  # → b'hi'
for fd in (r, w, got[0]):
    os.close(fd)
a.close()
b.close()

See also

Open in the full glossarydocs.python.orgReport an inaccuracy