doc_content stringlengths 1 386k | doc_id stringlengths 5 188 |
|---|---|
socket.has_ipv6
This constant contains a boolean value which indicates if IPv6 is supported on this platform. | python.library.socket#socket.has_ipv6 |
socket.HCI_FILTER
socket.HCI_TIME_STAMP
socket.HCI_DATA_DIR
For use with BTPROTO_HCI. HCI_FILTER is not available for NetBSD or DragonFlyBSD. HCI_TIME_STAMP and HCI_DATA_DIR are not available for FreeBSD, NetBSD, or DragonFlyBSD. | python.library.socket#socket.HCI_DATA_DIR |
socket.HCI_FILTER
socket.HCI_TIME_STAMP
socket.HCI_DATA_DIR
For use with BTPROTO_HCI. HCI_FILTER is not available for NetBSD or DragonFlyBSD. HCI_TIME_STAMP and HCI_DATA_DIR are not available for FreeBSD, NetBSD, or DragonFlyBSD. | python.library.socket#socket.HCI_FILTER |
socket.HCI_FILTER
socket.HCI_TIME_STAMP
socket.HCI_DATA_DIR
For use with BTPROTO_HCI. HCI_FILTER is not available for NetBSD or DragonFlyBSD. HCI_TIME_STAMP and HCI_DATA_DIR are not available for FreeBSD, NetBSD, or DragonFlyBSD. | python.library.socket#socket.HCI_TIME_STAMP |
exception socket.herror
A subclass of OSError, this exception is raised for address-related errors, i.e. for functions that use h_errno in the POSIX C API, including gethostbyname_ex() and gethostbyaddr(). The accompanying value is a pair (h_errno, string) representing an error returned by a library call. h_errno is a numeric value, while string represents the description of h_errno, as returned by the hstrerror() C function. Changed in version 3.3: This class was made a subclass of OSError. | python.library.socket#socket.herror |
socket.htonl(x)
Convert 32-bit positive integers from host to network byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 4-byte swap operation. | python.library.socket#socket.htonl |
socket.htons(x)
Convert 16-bit positive integers from host to network byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 2-byte swap operation. Deprecated since version 3.7: In case x does not fit in 16-bit unsigned integer, but does fit in a positive C int, it is silently truncated to 16-bit unsigned integer. This silent truncation feature is deprecated, and will raise an exception in future versions of Python. | python.library.socket#socket.htons |
socket.if_indextoname(if_index)
Return a network interface name corresponding to an interface index number. OSError if no interface with the given index exists. Availability: Unix, Windows. New in version 3.3. Changed in version 3.8: Windows support was added. See also “Interface name” is a name as documented in if_nameindex(). | python.library.socket#socket.if_indextoname |
socket.if_nameindex()
Return a list of network interface information (index int, name string) tuples. OSError if the system call fails. Availability: Unix, Windows. New in version 3.3. Changed in version 3.8: Windows support was added. Note On Windows network interfaces have different names in different contexts (all names are examples): UUID: {FB605B73-AAC2-49A6-9A2F-25416AEA0573}
name: ethernet_32770
friendly name: vEthernet (nat)
description: Hyper-V Virtual Ethernet Adapter
This function returns names of the second form from the list, ethernet_32770 in this example case. | python.library.socket#socket.if_nameindex |
socket.if_nametoindex(if_name)
Return a network interface index number corresponding to an interface name. OSError if no interface with the given name exists. Availability: Unix, Windows. New in version 3.3. Changed in version 3.8: Windows support was added. See also “Interface name” is a name as documented in if_nameindex(). | python.library.socket#socket.if_nametoindex |
socket.inet_aton(ip_string)
Convert an IPv4 address from dotted-quad string format (for example, ‘123.45.67.89’) to 32-bit packed binary format, as a bytes object four characters in length. This is useful when conversing with a program that uses the standard C library and needs objects of type struct in_addr, which is the C type for the 32-bit packed binary this function returns. inet_aton() also accepts strings with less than three dots; see the Unix manual page inet(3) for details. If the IPv4 address string passed to this function is invalid, OSError will be raised. Note that exactly what is valid depends on the underlying C implementation of inet_aton(). inet_aton() does not support IPv6, and inet_pton() should be used instead for IPv4/v6 dual stack support. | python.library.socket#socket.inet_aton |
socket.inet_ntoa(packed_ip)
Convert a 32-bit packed IPv4 address (a bytes-like object four bytes in length) to its standard dotted-quad string representation (for example, ‘123.45.67.89’). This is useful when conversing with a program that uses the standard C library and needs objects of type struct in_addr, which is the C type for the 32-bit packed binary data this function takes as an argument. If the byte sequence passed to this function is not exactly 4 bytes in length, OSError will be raised. inet_ntoa() does not support IPv6, and inet_ntop() should be used instead for IPv4/v6 dual stack support. Changed in version 3.5: Writable bytes-like object is now accepted. | python.library.socket#socket.inet_ntoa |
socket.inet_ntop(address_family, packed_ip)
Convert a packed IP address (a bytes-like object of some number of bytes) to its standard, family-specific string representation (for example, '7.10.0.5' or '5aef:2b::8'). inet_ntop() is useful when a library or network protocol returns an object of type struct in_addr (similar to inet_ntoa()) or struct in6_addr. Supported values for address_family are currently AF_INET and AF_INET6. If the bytes object packed_ip is not the correct length for the specified address family, ValueError will be raised. OSError is raised for errors from the call to inet_ntop(). Availability: Unix (maybe not all platforms), Windows. Changed in version 3.4: Windows support added Changed in version 3.5: Writable bytes-like object is now accepted. | python.library.socket#socket.inet_ntop |
socket.inet_pton(address_family, ip_string)
Convert an IP address from its family-specific string format to a packed, binary format. inet_pton() is useful when a library or network protocol calls for an object of type struct in_addr (similar to inet_aton()) or struct in6_addr. Supported values for address_family are currently AF_INET and AF_INET6. If the IP address string ip_string is invalid, OSError will be raised. Note that exactly what is valid depends on both the value of address_family and the underlying implementation of inet_pton(). Availability: Unix (maybe not all platforms), Windows. Changed in version 3.4: Windows support added | python.library.socket#socket.inet_pton |
socket.AF_VSOCK
socket.IOCTL_VM_SOCKETS_GET_LOCAL_CID
VMADDR*
SO_VM*
Constants for Linux host/guest communication. Availability: Linux >= 4.8. New in version 3.7. | python.library.socket#socket.IOCTL_VM_SOCKETS_GET_LOCAL_CID |
socket.ntohl(x)
Convert 32-bit positive integers from network to host byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 4-byte swap operation. | python.library.socket#socket.ntohl |
socket.ntohs(x)
Convert 16-bit positive integers from network to host byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 2-byte swap operation. Deprecated since version 3.7: In case x does not fit in 16-bit unsigned integer, but does fit in a positive C int, it is silently truncated to 16-bit unsigned integer. This silent truncation feature is deprecated, and will raise an exception in future versions of Python. | python.library.socket#socket.ntohs |
socket.AF_CAN
socket.PF_CAN
SOL_CAN_*
CAN_*
Many constants of these forms, documented in the Linux documentation, are also defined in the socket module. Availability: Linux >= 2.6.25. New in version 3.3. | python.library.socket#socket.PF_CAN |
socket.AF_PACKET
socket.PF_PACKET
PACKET_*
Many constants of these forms, documented in the Linux documentation, are also defined in the socket module. Availability: Linux >= 2.2. | python.library.socket#socket.PF_PACKET |
socket.AF_RDS
socket.PF_RDS
socket.SOL_RDS
RDS_*
Many constants of these forms, documented in the Linux documentation, are also defined in the socket module. Availability: Linux >= 2.6.30. New in version 3.3. | python.library.socket#socket.PF_RDS |
socket.recv_fds(sock, bufsize, maxfds[, flags])
Receive up to maxfds file descriptors from an AF_UNIX socket sock. Return (msg, list(fds), flags, addr). Consult recvmsg() for the documentation of these parameters. Availability: Unix supporting recvmsg() and SCM_RIGHTS mechanism. New in version 3.9. Note Any truncated integers at the end of the list of file descriptors. | python.library.socket#socket.recv_fds |
socket.send_fds(sock, buffers, fds[, flags[, address]])
Send the list of file descriptors fds over an AF_UNIX socket sock. The fds parameter is a sequence of file descriptors. Consult sendmsg() for the documentation of these parameters. Availability: Unix supporting sendmsg() and SCM_RIGHTS mechanism. New in version 3.9. | python.library.socket#socket.send_fds |
socket.setdefaulttimeout(timeout)
Set the default timeout in seconds (float) for new socket objects. When the socket module is first imported, the default is None. See settimeout() for possible values and their respective meanings. | python.library.socket#socket.setdefaulttimeout |
socket.sethostname(name)
Set the machine’s hostname to name. This will raise an OSError if you don’t have enough rights. Raises an auditing event socket.sethostname with argument name. Availability: Unix. New in version 3.3. | python.library.socket#socket.sethostname |
socket.SIO_RCVALL
socket.SIO_KEEPALIVE_VALS
socket.SIO_LOOPBACK_FAST_PATH
RCVALL_*
Constants for Windows’ WSAIoctl(). The constants are used as arguments to the ioctl() method of socket objects. Changed in version 3.6: SIO_LOOPBACK_FAST_PATH was added. | python.library.socket#socket.SIO_KEEPALIVE_VALS |
socket.SIO_RCVALL
socket.SIO_KEEPALIVE_VALS
socket.SIO_LOOPBACK_FAST_PATH
RCVALL_*
Constants for Windows’ WSAIoctl(). The constants are used as arguments to the ioctl() method of socket objects. Changed in version 3.6: SIO_LOOPBACK_FAST_PATH was added. | python.library.socket#socket.SIO_LOOPBACK_FAST_PATH |
socket.SIO_RCVALL
socket.SIO_KEEPALIVE_VALS
socket.SIO_LOOPBACK_FAST_PATH
RCVALL_*
Constants for Windows’ WSAIoctl(). The constants are used as arguments to the ioctl() method of socket objects. Changed in version 3.6: SIO_LOOPBACK_FAST_PATH was added. | python.library.socket#socket.SIO_RCVALL |
socket.socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None)
Create a new socket using the given address family, socket type and protocol number. The address family should be AF_INET (the default), AF_INET6, AF_UNIX, AF_CAN, AF_PACKET, or AF_RDS. The socket type should be SOCK_STREAM (the default), SOCK_DGRAM, SOCK_RAW or perhaps one of the other SOCK_ constants. The protocol number is usually zero and may be omitted or in the case where the address family is AF_CAN the protocol should be one of CAN_RAW, CAN_BCM, CAN_ISOTP or CAN_J1939. If fileno is specified, the values for family, type, and proto are auto-detected from the specified file descriptor. Auto-detection can be overruled by calling the function with explicit family, type, or proto arguments. This only affects how Python represents e.g. the return value of socket.getpeername() but not the actual OS resource. Unlike socket.fromfd(), fileno will return the same socket and not a duplicate. This may help close a detached socket using socket.close(). The newly created socket is non-inheritable. Raises an auditing event socket.__new__ with arguments self, family, type, protocol. Changed in version 3.3: The AF_CAN family was added. The AF_RDS family was added. Changed in version 3.4: The CAN_BCM protocol was added. Changed in version 3.4: The returned socket is now non-inheritable. Changed in version 3.7: The CAN_ISOTP protocol was added. Changed in version 3.7: When SOCK_NONBLOCK or SOCK_CLOEXEC bit flags are applied to type they are cleared, and socket.type will not reflect them. They are still passed to the underlying system socket() call. Therefore, sock = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM | socket.SOCK_NONBLOCK)
will still create a non-blocking socket on OSes that support SOCK_NONBLOCK, but sock.type will be set to socket.SOCK_STREAM. Changed in version 3.9: The CAN_J1939 protocol was added. | python.library.socket#socket.socket |
socket.accept()
Accept a connection. The socket must be bound to an address and listening for connections. The return value is a pair (conn, address) where conn is a new socket object usable to send and receive data on the connection, and address is the address bound to the socket on the other end of the connection. The newly created socket is non-inheritable. Changed in version 3.4: The socket is now non-inheritable. Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale). | python.library.socket#socket.socket.accept |
socket.bind(address)
Bind the socket to address. The socket must not already be bound. (The format of address depends on the address family — see above.) Raises an auditing event socket.bind with arguments self, address. | python.library.socket#socket.socket.bind |
socket.close()
Mark the socket closed. The underlying system resource (e.g. a file descriptor) is also closed when all file objects from makefile() are closed. Once that happens, all future operations on the socket object will fail. The remote end will receive no more data (after queued data is flushed). Sockets are automatically closed when they are garbage-collected, but it is recommended to close() them explicitly, or to use a with statement around them. Changed in version 3.6: OSError is now raised if an error occurs when the underlying close() call is made. Note close() releases the resource associated with a connection but does not necessarily close the connection immediately. If you want to close the connection in a timely fashion, call shutdown() before close(). | python.library.socket#socket.socket.close |
socket.connect(address)
Connect to a remote socket at address. (The format of address depends on the address family — see above.) If the connection is interrupted by a signal, the method waits until the connection completes, or raise a socket.timeout on timeout, if the signal handler doesn’t raise an exception and the socket is blocking or has a timeout. For non-blocking sockets, the method raises an InterruptedError exception if the connection is interrupted by a signal (or the exception raised by the signal handler). Raises an auditing event socket.connect with arguments self, address. Changed in version 3.5: The method now waits until the connection completes instead of raising an InterruptedError exception if the connection is interrupted by a signal, the signal handler doesn’t raise an exception and the socket is blocking or has a timeout (see the PEP 475 for the rationale). | python.library.socket#socket.socket.connect |
socket.connect_ex(address)
Like connect(address), but return an error indicator instead of raising an exception for errors returned by the C-level connect() call (other problems, such as “host not found,” can still raise exceptions). The error indicator is 0 if the operation succeeded, otherwise the value of the errno variable. This is useful to support, for example, asynchronous connects. Raises an auditing event socket.connect with arguments self, address. | python.library.socket#socket.socket.connect_ex |
socket.detach()
Put the socket object into closed state without actually closing the underlying file descriptor. The file descriptor is returned, and can be reused for other purposes. New in version 3.2. | python.library.socket#socket.socket.detach |
socket.dup()
Duplicate the socket. The newly created socket is non-inheritable. Changed in version 3.4: The socket is now non-inheritable. | python.library.socket#socket.socket.dup |
socket.family
The socket family. | python.library.socket#socket.socket.family |
socket.fileno()
Return the socket’s file descriptor (a small integer), or -1 on failure. This is useful with select.select(). Under Windows the small integer returned by this method cannot be used where a file descriptor can be used (such as os.fdopen()). Unix does not have this limitation. | python.library.socket#socket.socket.fileno |
socket.getblocking()
Return True if socket is in blocking mode, False if in non-blocking. This is equivalent to checking socket.gettimeout() == 0. New in version 3.7. | python.library.socket#socket.socket.getblocking |
socket.getpeername()
Return the remote address to which the socket is connected. This is useful to find out the port number of a remote IPv4/v6 socket, for instance. (The format of the address returned depends on the address family — see above.) On some systems this function is not supported. | python.library.socket#socket.socket.getpeername |
socket.getsockname()
Return the socket’s own address. This is useful to find out the port number of an IPv4/v6 socket, for instance. (The format of the address returned depends on the address family — see above.) | python.library.socket#socket.socket.getsockname |
socket.getsockopt(level, optname[, buflen])
Return the value of the given socket option (see the Unix man page getsockopt(2)). The needed symbolic constants (SO_* etc.) are defined in this module. If buflen is absent, an integer option is assumed and its integer value is returned by the function. If buflen is present, it specifies the maximum length of the buffer used to receive the option in, and this buffer is returned as a bytes object. It is up to the caller to decode the contents of the buffer (see the optional built-in module struct for a way to decode C structures encoded as byte strings). | python.library.socket#socket.socket.getsockopt |
socket.gettimeout()
Return the timeout in seconds (float) associated with socket operations, or None if no timeout is set. This reflects the last call to setblocking() or settimeout(). | python.library.socket#socket.socket.gettimeout |
socket.get_inheritable()
Get the inheritable flag of the socket’s file descriptor or socket’s handle: True if the socket can be inherited in child processes, False if it cannot. New in version 3.4. | python.library.socket#socket.socket.get_inheritable |
socket.ioctl(control, option)
Platform
Windows The ioctl() method is a limited interface to the WSAIoctl system interface. Please refer to the Win32 documentation for more information. On other platforms, the generic fcntl.fcntl() and fcntl.ioctl() functions may be used; they accept a socket object as their first argument. Currently only the following control codes are supported: SIO_RCVALL, SIO_KEEPALIVE_VALS, and SIO_LOOPBACK_FAST_PATH. Changed in version 3.6: SIO_LOOPBACK_FAST_PATH was added. | python.library.socket#socket.socket.ioctl |
socket.listen([backlog])
Enable a server to accept connections. If backlog is specified, it must be at least 0 (if it is lower, it is set to 0); it specifies the number of unaccepted connections that the system will allow before refusing new connections. If not specified, a default reasonable value is chosen. Changed in version 3.5: The backlog parameter is now optional. | python.library.socket#socket.socket.listen |
socket.makefile(mode='r', buffering=None, *, encoding=None, errors=None, newline=None)
Return a file object associated with the socket. The exact returned type depends on the arguments given to makefile(). These arguments are interpreted the same way as by the built-in open() function, except the only supported mode values are 'r' (default), 'w' and 'b'. The socket must be in blocking mode; it can have a timeout, but the file object’s internal buffer may end up in an inconsistent state if a timeout occurs. Closing the file object returned by makefile() won’t close the original socket unless all other file objects have been closed and socket.close() has been called on the socket object. Note On Windows, the file-like object created by makefile() cannot be used where a file object with a file descriptor is expected, such as the stream arguments of subprocess.Popen(). | python.library.socket#socket.socket.makefile |
socket.proto
The socket protocol. | python.library.socket#socket.socket.proto |
socket.recv(bufsize[, flags])
Receive data from the socket. The return value is a bytes object representing the data received. The maximum amount of data to be received at once is specified by bufsize. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero. Note For best match with hardware and network realities, the value of bufsize should be a relatively small power of 2, for example, 4096. Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale). | python.library.socket#socket.socket.recv |
socket.recvfrom(bufsize[, flags])
Receive data from the socket. The return value is a pair (bytes, address) where bytes is a bytes object representing the data received and address is the address of the socket sending the data. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero. (The format of address depends on the address family — see above.) Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale). Changed in version 3.7: For multicast IPv6 address, first item of address does not contain %scope_id part anymore. In order to get full IPv6 address use getnameinfo(). | python.library.socket#socket.socket.recvfrom |
socket.recvfrom_into(buffer[, nbytes[, flags]])
Receive data from the socket, writing it into buffer instead of creating a new bytestring. The return value is a pair (nbytes, address) where nbytes is the number of bytes received and address is the address of the socket sending the data. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero. (The format of address depends on the address family — see above.) | python.library.socket#socket.socket.recvfrom_into |
socket.recvmsg(bufsize[, ancbufsize[, flags]])
Receive normal data (up to bufsize bytes) and ancillary data from the socket. The ancbufsize argument sets the size in bytes of the internal buffer used to receive the ancillary data; it defaults to 0, meaning that no ancillary data will be received. Appropriate buffer sizes for ancillary data can be calculated using CMSG_SPACE() or CMSG_LEN(), and items which do not fit into the buffer might be truncated or discarded. The flags argument defaults to 0 and has the same meaning as for recv(). The return value is a 4-tuple: (data, ancdata, msg_flags,
address). The data item is a bytes object holding the non-ancillary data received. The ancdata item is a list of zero or more tuples (cmsg_level, cmsg_type, cmsg_data) representing the ancillary data (control messages) received: cmsg_level and cmsg_type are integers specifying the protocol level and protocol-specific type respectively, and cmsg_data is a bytes object holding the associated data. The msg_flags item is the bitwise OR of various flags indicating conditions on the received message; see your system documentation for details. If the receiving socket is unconnected, address is the address of the sending socket, if available; otherwise, its value is unspecified. On some systems, sendmsg() and recvmsg() can be used to pass file descriptors between processes over an AF_UNIX socket. When this facility is used (it is often restricted to SOCK_STREAM sockets), recvmsg() will return, in its ancillary data, items of the form (socket.SOL_SOCKET,
socket.SCM_RIGHTS, fds), where fds is a bytes object representing the new file descriptors as a binary array of the native C int type. If recvmsg() raises an exception after the system call returns, it will first attempt to close any file descriptors received via this mechanism. Some systems do not indicate the truncated length of ancillary data items which have been only partially received. If an item appears to extend beyond the end of the buffer, recvmsg() will issue a RuntimeWarning, and will return the part of it which is inside the buffer provided it has not been truncated before the start of its associated data. On systems which support the SCM_RIGHTS mechanism, the following function will receive up to maxfds file descriptors, returning the message data and a list containing the descriptors (while ignoring unexpected conditions such as unrelated control messages being received). See also sendmsg(). import socket, array
def recv_fds(sock, msglen, maxfds):
fds = array.array("i") # Array of ints
msg, ancdata, flags, addr = sock.recvmsg(msglen, socket.CMSG_LEN(maxfds * fds.itemsize))
for cmsg_level, cmsg_type, cmsg_data in ancdata:
if cmsg_level == socket.SOL_SOCKET and cmsg_type == socket.SCM_RIGHTS:
# Append data, ignoring any truncated integers at the end.
fds.frombytes(cmsg_data[:len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
return msg, list(fds)
Availability: most Unix platforms, possibly others. New in version 3.3. Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale). | python.library.socket#socket.socket.recvmsg |
socket.recvmsg_into(buffers[, ancbufsize[, flags]])
Receive normal data and ancillary data from the socket, behaving as recvmsg() would, but scatter the non-ancillary data into a series of buffers instead of returning a new bytes object. The buffers argument must be an iterable of objects that export writable buffers (e.g. bytearray objects); these will be filled with successive chunks of the non-ancillary data until it has all been written or there are no more buffers. The operating system may set a limit (sysconf() value SC_IOV_MAX) on the number of buffers that can be used. The ancbufsize and flags arguments have the same meaning as for recvmsg(). The return value is a 4-tuple: (nbytes, ancdata, msg_flags,
address), where nbytes is the total number of bytes of non-ancillary data written into the buffers, and ancdata, msg_flags and address are the same as for recvmsg(). Example: >>> import socket
>>> s1, s2 = socket.socketpair()
>>> b1 = bytearray(b'----')
>>> b2 = bytearray(b'0123456789')
>>> b3 = bytearray(b'--------------')
>>> s1.send(b'Mary had a little lamb')
22
>>> s2.recvmsg_into([b1, memoryview(b2)[2:9], b3])
(22, [], 0, None)
>>> [b1, b2, b3]
[bytearray(b'Mary'), bytearray(b'01 had a 9'), bytearray(b'little lamb---')]
Availability: most Unix platforms, possibly others. New in version 3.3. | python.library.socket#socket.socket.recvmsg_into |
socket.recv_into(buffer[, nbytes[, flags]])
Receive up to nbytes bytes from the socket, storing the data into a buffer rather than creating a new bytestring. If nbytes is not specified (or 0), receive up to the size available in the given buffer. Returns the number of bytes received. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero. | python.library.socket#socket.socket.recv_into |
socket.send(bytes[, flags])
Send data to the socket. The socket must be connected to a remote socket. The optional flags argument has the same meaning as for recv() above. Returns the number of bytes sent. Applications are responsible for checking that all data has been sent; if only some of the data was transmitted, the application needs to attempt delivery of the remaining data. For further information on this topic, consult the Socket Programming HOWTO. Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale). | python.library.socket#socket.socket.send |
socket.sendall(bytes[, flags])
Send data to the socket. The socket must be connected to a remote socket. The optional flags argument has the same meaning as for recv() above. Unlike send(), this method continues to send data from bytes until either all data has been sent or an error occurs. None is returned on success. On error, an exception is raised, and there is no way to determine how much data, if any, was successfully sent. Changed in version 3.5: The socket timeout is no more reset each time data is sent successfully. The socket timeout is now the maximum total duration to send all data. Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale). | python.library.socket#socket.socket.sendall |
socket.sendfile(file, offset=0, count=None)
Send a file until EOF is reached by using high-performance os.sendfile and return the total number of bytes which were sent. file must be a regular file object opened in binary mode. If os.sendfile is not available (e.g. Windows) or file is not a regular file send() will be used instead. offset tells from where to start reading the file. If specified, count is the total number of bytes to transmit as opposed to sending the file until EOF is reached. File position is updated on return or also in case of error in which case file.tell() can be used to figure out the number of bytes which were sent. The socket must be of SOCK_STREAM type. Non-blocking sockets are not supported. New in version 3.5. | python.library.socket#socket.socket.sendfile |
socket.sendmsg(buffers[, ancdata[, flags[, address]]])
Send normal and ancillary data to the socket, gathering the non-ancillary data from a series of buffers and concatenating it into a single message. The buffers argument specifies the non-ancillary data as an iterable of bytes-like objects (e.g. bytes objects); the operating system may set a limit (sysconf() value SC_IOV_MAX) on the number of buffers that can be used. The ancdata argument specifies the ancillary data (control messages) as an iterable of zero or more tuples (cmsg_level, cmsg_type, cmsg_data), where cmsg_level and cmsg_type are integers specifying the protocol level and protocol-specific type respectively, and cmsg_data is a bytes-like object holding the associated data. Note that some systems (in particular, systems without CMSG_SPACE()) might support sending only one control message per call. The flags argument defaults to 0 and has the same meaning as for send(). If address is supplied and not None, it sets a destination address for the message. The return value is the number of bytes of non-ancillary data sent. The following function sends the list of file descriptors fds over an AF_UNIX socket, on systems which support the SCM_RIGHTS mechanism. See also recvmsg(). import socket, array
def send_fds(sock, msg, fds):
return sock.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", fds))])
Availability: most Unix platforms, possibly others. Raises an auditing event socket.sendmsg with arguments self, address. New in version 3.3. Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale). | python.library.socket#socket.socket.sendmsg |
socket.sendmsg_afalg([msg, ]*, op[, iv[, assoclen[, flags]]])
Specialized version of sendmsg() for AF_ALG socket. Set mode, IV, AEAD associated data length and flags for AF_ALG socket. Availability: Linux >= 2.6.38. New in version 3.6. | python.library.socket#socket.socket.sendmsg_afalg |
socket.sendto(bytes, address)
socket.sendto(bytes, flags, address)
Send data to the socket. The socket should not be connected to a remote socket, since the destination socket is specified by address. The optional flags argument has the same meaning as for recv() above. Return the number of bytes sent. (The format of address depends on the address family — see above.) Raises an auditing event socket.sendto with arguments self, address. Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale). | python.library.socket#socket.socket.sendto |
socket.setblocking(flag)
Set blocking or non-blocking mode of the socket: if flag is false, the socket is set to non-blocking, else to blocking mode. This method is a shorthand for certain settimeout() calls:
sock.setblocking(True) is equivalent to sock.settimeout(None)
sock.setblocking(False) is equivalent to sock.settimeout(0.0)
Changed in version 3.7: The method no longer applies SOCK_NONBLOCK flag on socket.type. | python.library.socket#socket.socket.setblocking |
socket.setsockopt(level, optname, value: int) | python.library.socket#socket.socket.setsockopt |
socket.settimeout(value)
Set a timeout on blocking socket operations. The value argument can be a nonnegative floating point number expressing seconds, or None. If a non-zero value is given, subsequent socket operations will raise a timeout exception if the timeout period value has elapsed before the operation has completed. If zero is given, the socket is put in non-blocking mode. If None is given, the socket is put in blocking mode. For further information, please consult the notes on socket timeouts. Changed in version 3.7: The method no longer toggles SOCK_NONBLOCK flag on socket.type. | python.library.socket#socket.socket.settimeout |
socket.set_inheritable(inheritable)
Set the inheritable flag of the socket’s file descriptor or socket’s handle. New in version 3.4. | python.library.socket#socket.socket.set_inheritable |
socket.share(process_id)
Duplicate a socket and prepare it for sharing with a target process. The target process must be provided with process_id. The resulting bytes object can then be passed to the target process using some form of interprocess communication and the socket can be recreated there using fromshare(). Once this method has been called, it is safe to close the socket since the operating system has already duplicated it for the target process. Availability: Windows. New in version 3.3. | python.library.socket#socket.socket.share |
socket.shutdown(how)
Shut down one or both halves of the connection. If how is SHUT_RD, further receives are disallowed. If how is SHUT_WR, further sends are disallowed. If how is SHUT_RDWR, further sends and receives are disallowed. | python.library.socket#socket.socket.shutdown |
socket.type
The socket type. | python.library.socket#socket.socket.type |
socket.socketpair([family[, type[, proto]]])
Build a pair of connected socket objects using the given address family, socket type, and protocol number. Address family, socket type, and protocol number are as for the socket() function above. The default family is AF_UNIX if defined on the platform; otherwise, the default is AF_INET. The newly created sockets are non-inheritable. Changed in version 3.2: The returned socket objects now support the whole socket API, rather than a subset. Changed in version 3.4: The returned sockets are now non-inheritable. Changed in version 3.5: Windows support added. | python.library.socket#socket.socketpair |
socket.SocketType
This is a Python type object that represents the socket object type. It is the same as type(socket(...)). | python.library.socket#socket.SocketType |
socket.SOCK_CLOEXEC
socket.SOCK_NONBLOCK
These two constants, if defined, can be combined with the socket types and allow you to set some flags atomically (thus avoiding possible race conditions and the need for separate calls). See also Secure File Descriptor Handling for a more thorough explanation. Availability: Linux >= 2.6.27. New in version 3.2. | python.library.socket#socket.SOCK_CLOEXEC |
socket.SOCK_STREAM
socket.SOCK_DGRAM
socket.SOCK_RAW
socket.SOCK_RDM
socket.SOCK_SEQPACKET
These constants represent the socket types, used for the second argument to socket(). More constants may be available depending on the system. (Only SOCK_STREAM and SOCK_DGRAM appear to be generally useful.) | python.library.socket#socket.SOCK_DGRAM |
socket.SOCK_CLOEXEC
socket.SOCK_NONBLOCK
These two constants, if defined, can be combined with the socket types and allow you to set some flags atomically (thus avoiding possible race conditions and the need for separate calls). See also Secure File Descriptor Handling for a more thorough explanation. Availability: Linux >= 2.6.27. New in version 3.2. | python.library.socket#socket.SOCK_NONBLOCK |
socket.SOCK_STREAM
socket.SOCK_DGRAM
socket.SOCK_RAW
socket.SOCK_RDM
socket.SOCK_SEQPACKET
These constants represent the socket types, used for the second argument to socket(). More constants may be available depending on the system. (Only SOCK_STREAM and SOCK_DGRAM appear to be generally useful.) | python.library.socket#socket.SOCK_RAW |
socket.SOCK_STREAM
socket.SOCK_DGRAM
socket.SOCK_RAW
socket.SOCK_RDM
socket.SOCK_SEQPACKET
These constants represent the socket types, used for the second argument to socket(). More constants may be available depending on the system. (Only SOCK_STREAM and SOCK_DGRAM appear to be generally useful.) | python.library.socket#socket.SOCK_RDM |
socket.SOCK_STREAM
socket.SOCK_DGRAM
socket.SOCK_RAW
socket.SOCK_RDM
socket.SOCK_SEQPACKET
These constants represent the socket types, used for the second argument to socket(). More constants may be available depending on the system. (Only SOCK_STREAM and SOCK_DGRAM appear to be generally useful.) | python.library.socket#socket.SOCK_SEQPACKET |
socket.SOCK_STREAM
socket.SOCK_DGRAM
socket.SOCK_RAW
socket.SOCK_RDM
socket.SOCK_SEQPACKET
These constants represent the socket types, used for the second argument to socket(). More constants may be available depending on the system. (Only SOCK_STREAM and SOCK_DGRAM appear to be generally useful.) | python.library.socket#socket.SOCK_STREAM |
socket.AF_ALG
socket.SOL_ALG
ALG_*
Constants for Linux Kernel cryptography. Availability: Linux >= 2.6.38. New in version 3.6. | python.library.socket#socket.SOL_ALG |
socket.AF_RDS
socket.PF_RDS
socket.SOL_RDS
RDS_*
Many constants of these forms, documented in the Linux documentation, are also defined in the socket module. Availability: Linux >= 2.6.30. New in version 3.3. | python.library.socket#socket.SOL_RDS |
SO_*
socket.SOMAXCONN
MSG_*
SOL_*
SCM_*
IPPROTO_*
IPPORT_*
INADDR_*
IP_*
IPV6_*
EAI_*
AI_*
NI_*
TCP_*
Many constants of these forms, documented in the Unix documentation on sockets and/or the IP protocol, are also defined in the socket module. They are generally used in arguments to the setsockopt() and getsockopt() methods of socket objects. In most cases, only those symbols that are defined in the Unix header files are defined; for a few symbols, default values are provided. Changed in version 3.6: SO_DOMAIN, SO_PROTOCOL, SO_PEERSEC, SO_PASSSEC, TCP_USER_TIMEOUT, TCP_CONGESTION were added. Changed in version 3.6.5: On Windows, TCP_FASTOPEN, TCP_KEEPCNT appear if run-time Windows supports. Changed in version 3.7: TCP_NOTSENT_LOWAT was added. On Windows, TCP_KEEPIDLE, TCP_KEEPINTVL appear if run-time Windows supports. | python.library.socket#socket.SOMAXCONN |
exception socket.timeout
A subclass of OSError, this exception is raised when a timeout occurs on a socket which has had timeouts enabled via a prior call to settimeout() (or implicitly through setdefaulttimeout()). The accompanying value is a string whose value is currently always “timed out”. Changed in version 3.3: This class was made a subclass of OSError. | python.library.socket#socket.timeout |
socketserver — A framework for network servers Source code: Lib/socketserver.py The socketserver module simplifies the task of writing network servers. There are four basic concrete server classes:
class socketserver.TCPServer(server_address, RequestHandlerClass, bind_and_activate=True)
This uses the Internet TCP protocol, which provides for continuous streams of data between the client and server. If bind_and_activate is true, the constructor automatically attempts to invoke server_bind() and server_activate(). The other parameters are passed to the BaseServer base class.
class socketserver.UDPServer(server_address, RequestHandlerClass, bind_and_activate=True)
This uses datagrams, which are discrete packets of information that may arrive out of order or be lost while in transit. The parameters are the same as for TCPServer.
class socketserver.UnixStreamServer(server_address, RequestHandlerClass, bind_and_activate=True)
class socketserver.UnixDatagramServer(server_address, RequestHandlerClass, bind_and_activate=True)
These more infrequently used classes are similar to the TCP and UDP classes, but use Unix domain sockets; they’re not available on non-Unix platforms. The parameters are the same as for TCPServer.
These four classes process requests synchronously; each request must be completed before the next request can be started. This isn’t suitable if each request takes a long time to complete, because it requires a lot of computation, or because it returns a lot of data which the client is slow to process. The solution is to create a separate process or thread to handle each request; the ForkingMixIn and ThreadingMixIn mix-in classes can be used to support asynchronous behaviour. Creating a server requires several steps. First, you must create a request handler class by subclassing the BaseRequestHandler class and overriding its handle() method; this method will process incoming requests. Second, you must instantiate one of the server classes, passing it the server’s address and the request handler class. It is recommended to use the server in a with statement. Then call the handle_request() or serve_forever() method of the server object to process one or many requests. Finally, call server_close() to close the socket (unless you used a with statement). When inheriting from ThreadingMixIn for threaded connection behavior, you should explicitly declare how you want your threads to behave on an abrupt shutdown. The ThreadingMixIn class defines an attribute daemon_threads, which indicates whether or not the server should wait for thread termination. You should set the flag explicitly if you would like threads to behave autonomously; the default is False, meaning that Python will not exit until all threads created by ThreadingMixIn have exited. Server classes have the same external methods and attributes, no matter what network protocol they use. Server Creation Notes There are five classes in an inheritance diagram, four of which represent synchronous servers of four types: +------------+
| BaseServer |
+------------+
|
v
+-----------+ +------------------+
| TCPServer |------->| UnixStreamServer |
+-----------+ +------------------+
|
v
+-----------+ +--------------------+
| UDPServer |------->| UnixDatagramServer |
+-----------+ +--------------------+
Note that UnixDatagramServer derives from UDPServer, not from UnixStreamServer — the only difference between an IP and a Unix stream server is the address family, which is simply repeated in both Unix server classes.
class socketserver.ForkingMixIn
class socketserver.ThreadingMixIn
Forking and threading versions of each type of server can be created using these mix-in classes. For instance, ThreadingUDPServer is created as follows: class ThreadingUDPServer(ThreadingMixIn, UDPServer):
pass
The mix-in class comes first, since it overrides a method defined in UDPServer. Setting the various attributes also changes the behavior of the underlying server mechanism. ForkingMixIn and the Forking classes mentioned below are only available on POSIX platforms that support fork(). socketserver.ForkingMixIn.server_close() waits until all child processes complete, except if socketserver.ForkingMixIn.block_on_close attribute is false. socketserver.ThreadingMixIn.server_close() waits until all non-daemon threads complete, except if socketserver.ThreadingMixIn.block_on_close attribute is false. Use daemonic threads by setting ThreadingMixIn.daemon_threads to True to not wait until threads complete. Changed in version 3.7: socketserver.ForkingMixIn.server_close() and socketserver.ThreadingMixIn.server_close() now waits until all child processes and non-daemonic threads complete. Add a new socketserver.ForkingMixIn.block_on_close class attribute to opt-in for the pre-3.7 behaviour.
class socketserver.ForkingTCPServer
class socketserver.ForkingUDPServer
class socketserver.ThreadingTCPServer
class socketserver.ThreadingUDPServer
These classes are pre-defined using the mix-in classes.
To implement a service, you must derive a class from BaseRequestHandler and redefine its handle() method. You can then run various versions of the service by combining one of the server classes with your request handler class. The request handler class must be different for datagram or stream services. This can be hidden by using the handler subclasses StreamRequestHandler or DatagramRequestHandler. Of course, you still have to use your head! For instance, it makes no sense to use a forking server if the service contains state in memory that can be modified by different requests, since the modifications in the child process would never reach the initial state kept in the parent process and passed to each child. In this case, you can use a threading server, but you will probably have to use locks to protect the integrity of the shared data. On the other hand, if you are building an HTTP server where all data is stored externally (for instance, in the file system), a synchronous class will essentially render the service “deaf” while one request is being handled – which may be for a very long time if a client is slow to receive all the data it has requested. Here a threading or forking server is appropriate. In some cases, it may be appropriate to process part of a request synchronously, but to finish processing in a forked child depending on the request data. This can be implemented by using a synchronous server and doing an explicit fork in the request handler class handle() method. Another approach to handling multiple simultaneous requests in an environment that supports neither threads nor fork() (or where these are too expensive or inappropriate for the service) is to maintain an explicit table of partially finished requests and to use selectors to decide which request to work on next (or whether to handle a new incoming request). This is particularly important for stream services where each client can potentially be connected for a long time (if threads or subprocesses cannot be used). See asyncore for another way to manage this. Server Objects
class socketserver.BaseServer(server_address, RequestHandlerClass)
This is the superclass of all Server objects in the module. It defines the interface, given below, but does not implement most of the methods, which is done in subclasses. The two parameters are stored in the respective server_address and RequestHandlerClass attributes.
fileno()
Return an integer file descriptor for the socket on which the server is listening. This function is most commonly passed to selectors, to allow monitoring multiple servers in the same process.
handle_request()
Process a single request. This function calls the following methods in order: get_request(), verify_request(), and process_request(). If the user-provided handle() method of the handler class raises an exception, the server’s handle_error() method will be called. If no request is received within timeout seconds, handle_timeout() will be called and handle_request() will return.
serve_forever(poll_interval=0.5)
Handle requests until an explicit shutdown() request. Poll for shutdown every poll_interval seconds. Ignores the timeout attribute. It also calls service_actions(), which may be used by a subclass or mixin to provide actions specific to a given service. For example, the ForkingMixIn class uses service_actions() to clean up zombie child processes. Changed in version 3.3: Added service_actions call to the serve_forever method.
service_actions()
This is called in the serve_forever() loop. This method can be overridden by subclasses or mixin classes to perform actions specific to a given service, such as cleanup actions. New in version 3.3.
shutdown()
Tell the serve_forever() loop to stop and wait until it does. shutdown() must be called while serve_forever() is running in a different thread otherwise it will deadlock.
server_close()
Clean up the server. May be overridden.
address_family
The family of protocols to which the server’s socket belongs. Common examples are socket.AF_INET and socket.AF_UNIX.
RequestHandlerClass
The user-provided request handler class; an instance of this class is created for each request.
server_address
The address on which the server is listening. The format of addresses varies depending on the protocol family; see the documentation for the socket module for details. For Internet protocols, this is a tuple containing a string giving the address, and an integer port number: ('127.0.0.1', 80), for example.
socket
The socket object on which the server will listen for incoming requests.
The server classes support the following class variables:
allow_reuse_address
Whether the server will allow the reuse of an address. This defaults to False, and can be set in subclasses to change the policy.
request_queue_size
The size of the request queue. If it takes a long time to process a single request, any requests that arrive while the server is busy are placed into a queue, up to request_queue_size requests. Once the queue is full, further requests from clients will get a “Connection denied” error. The default value is usually 5, but this can be overridden by subclasses.
socket_type
The type of socket used by the server; socket.SOCK_STREAM and socket.SOCK_DGRAM are two common values.
timeout
Timeout duration, measured in seconds, or None if no timeout is desired. If handle_request() receives no incoming requests within the timeout period, the handle_timeout() method is called.
There are various server methods that can be overridden by subclasses of base server classes like TCPServer; these methods aren’t useful to external users of the server object.
finish_request(request, client_address)
Actually processes the request by instantiating RequestHandlerClass and calling its handle() method.
get_request()
Must accept a request from the socket, and return a 2-tuple containing the new socket object to be used to communicate with the client, and the client’s address.
handle_error(request, client_address)
This function is called if the handle() method of a RequestHandlerClass instance raises an exception. The default action is to print the traceback to standard error and continue handling further requests. Changed in version 3.6: Now only called for exceptions derived from the Exception class.
handle_timeout()
This function is called when the timeout attribute has been set to a value other than None and the timeout period has passed with no requests being received. The default action for forking servers is to collect the status of any child processes that have exited, while in threading servers this method does nothing.
process_request(request, client_address)
Calls finish_request() to create an instance of the RequestHandlerClass. If desired, this function can create a new process or thread to handle the request; the ForkingMixIn and ThreadingMixIn classes do this.
server_activate()
Called by the server’s constructor to activate the server. The default behavior for a TCP server just invokes listen() on the server’s socket. May be overridden.
server_bind()
Called by the server’s constructor to bind the socket to the desired address. May be overridden.
verify_request(request, client_address)
Must return a Boolean value; if the value is True, the request will be processed, and if it’s False, the request will be denied. This function can be overridden to implement access controls for a server. The default implementation always returns True.
Changed in version 3.6: Support for the context manager protocol was added. Exiting the context manager is equivalent to calling server_close().
Request Handler Objects
class socketserver.BaseRequestHandler
This is the superclass of all request handler objects. It defines the interface, given below. A concrete request handler subclass must define a new handle() method, and can override any of the other methods. A new instance of the subclass is created for each request.
setup()
Called before the handle() method to perform any initialization actions required. The default implementation does nothing.
handle()
This function must do all the work required to service a request. The default implementation does nothing. Several instance attributes are available to it; the request is available as self.request; the client address as self.client_address; and the server instance as self.server, in case it needs access to per-server information. The type of self.request is different for datagram or stream services. For stream services, self.request is a socket object; for datagram services, self.request is a pair of string and socket.
finish()
Called after the handle() method to perform any clean-up actions required. The default implementation does nothing. If setup() raises an exception, this function will not be called.
class socketserver.StreamRequestHandler
class socketserver.DatagramRequestHandler
These BaseRequestHandler subclasses override the setup() and finish() methods, and provide self.rfile and self.wfile attributes. The self.rfile and self.wfile attributes can be read or written, respectively, to get the request data or return data to the client. The rfile attributes of both classes support the io.BufferedIOBase readable interface, and DatagramRequestHandler.wfile supports the io.BufferedIOBase writable interface. Changed in version 3.6: StreamRequestHandler.wfile also supports the io.BufferedIOBase writable interface.
Examples
socketserver.TCPServer Example This is the server side: import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
"""
The request handler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print("{} wrote:".format(self.client_address[0]))
print(self.data)
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
# Create the server, binding to localhost on port 9999
with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server:
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
An alternative request handler class that makes use of streams (file-like objects that simplify communication by providing the standard file interface): class MyTCPHandler(socketserver.StreamRequestHandler):
def handle(self):
# self.rfile is a file-like object created by the handler;
# we can now use e.g. readline() instead of raw recv() calls
self.data = self.rfile.readline().strip()
print("{} wrote:".format(self.client_address[0]))
print(self.data)
# Likewise, self.wfile is a file-like object used to write back
# to the client
self.wfile.write(self.data.upper())
The difference is that the readline() call in the second handler will call recv() multiple times until it encounters a newline character, while the single recv() call in the first handler will just return what has been sent from the client in one sendall() call. This is the client side: import socket
import sys
HOST, PORT = "localhost", 9999
data = " ".join(sys.argv[1:])
# Create a socket (SOCK_STREAM means a TCP socket)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
# Connect to server and send data
sock.connect((HOST, PORT))
sock.sendall(bytes(data + "\n", "utf-8"))
# Receive data from the server and shut down
received = str(sock.recv(1024), "utf-8")
print("Sent: {}".format(data))
print("Received: {}".format(received))
The output of the example should look something like this: Server: $ python TCPServer.py
127.0.0.1 wrote:
b'hello world with TCP'
127.0.0.1 wrote:
b'python is nice'
Client: $ python TCPClient.py hello world with TCP
Sent: hello world with TCP
Received: HELLO WORLD WITH TCP
$ python TCPClient.py python is nice
Sent: python is nice
Received: PYTHON IS NICE
socketserver.UDPServer Example This is the server side: import socketserver
class MyUDPHandler(socketserver.BaseRequestHandler):
"""
This class works similar to the TCP handler class, except that
self.request consists of a pair of data and client socket, and since
there is no connection the client address must be given explicitly
when sending data back via sendto().
"""
def handle(self):
data = self.request[0].strip()
socket = self.request[1]
print("{} wrote:".format(self.client_address[0]))
print(data)
socket.sendto(data.upper(), self.client_address)
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
with socketserver.UDPServer((HOST, PORT), MyUDPHandler) as server:
server.serve_forever()
This is the client side: import socket
import sys
HOST, PORT = "localhost", 9999
data = " ".join(sys.argv[1:])
# SOCK_DGRAM is the socket type to use for UDP sockets
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# As you can see, there is no connect() call; UDP has no connections.
# Instead, data is directly sent to the recipient via sendto().
sock.sendto(bytes(data + "\n", "utf-8"), (HOST, PORT))
received = str(sock.recv(1024), "utf-8")
print("Sent: {}".format(data))
print("Received: {}".format(received))
The output of the example should look exactly like for the TCP server example. Asynchronous Mixins To build asynchronous handlers, use the ThreadingMixIn and ForkingMixIn classes. An example for the ThreadingMixIn class: import socket
import threading
import socketserver
class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
def handle(self):
data = str(self.request.recv(1024), 'ascii')
cur_thread = threading.current_thread()
response = bytes("{}: {}".format(cur_thread.name, data), 'ascii')
self.request.sendall(response)
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
pass
def client(ip, port, message):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect((ip, port))
sock.sendall(bytes(message, 'ascii'))
response = str(sock.recv(1024), 'ascii')
print("Received: {}".format(response))
if __name__ == "__main__":
# Port 0 means to select an arbitrary unused port
HOST, PORT = "localhost", 0
server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
with server:
ip, port = server.server_address
# Start a thread with the server -- that thread will then start one
# more thread for each request
server_thread = threading.Thread(target=server.serve_forever)
# Exit the server thread when the main thread terminates
server_thread.daemon = True
server_thread.start()
print("Server loop running in thread:", server_thread.name)
client(ip, port, "Hello World 1")
client(ip, port, "Hello World 2")
client(ip, port, "Hello World 3")
server.shutdown()
The output of the example should look something like this: $ python ThreadedTCPServer.py
Server loop running in thread: Thread-1
Received: Thread-2: Hello World 1
Received: Thread-3: Hello World 2
Received: Thread-4: Hello World 3
The ForkingMixIn class is used in the same way, except that the server will spawn a new process for each request. Available only on POSIX platforms that support fork(). | python.library.socketserver |
class socketserver.BaseRequestHandler
This is the superclass of all request handler objects. It defines the interface, given below. A concrete request handler subclass must define a new handle() method, and can override any of the other methods. A new instance of the subclass is created for each request.
setup()
Called before the handle() method to perform any initialization actions required. The default implementation does nothing.
handle()
This function must do all the work required to service a request. The default implementation does nothing. Several instance attributes are available to it; the request is available as self.request; the client address as self.client_address; and the server instance as self.server, in case it needs access to per-server information. The type of self.request is different for datagram or stream services. For stream services, self.request is a socket object; for datagram services, self.request is a pair of string and socket.
finish()
Called after the handle() method to perform any clean-up actions required. The default implementation does nothing. If setup() raises an exception, this function will not be called. | python.library.socketserver#socketserver.BaseRequestHandler |
finish()
Called after the handle() method to perform any clean-up actions required. The default implementation does nothing. If setup() raises an exception, this function will not be called. | python.library.socketserver#socketserver.BaseRequestHandler.finish |
handle()
This function must do all the work required to service a request. The default implementation does nothing. Several instance attributes are available to it; the request is available as self.request; the client address as self.client_address; and the server instance as self.server, in case it needs access to per-server information. The type of self.request is different for datagram or stream services. For stream services, self.request is a socket object; for datagram services, self.request is a pair of string and socket. | python.library.socketserver#socketserver.BaseRequestHandler.handle |
setup()
Called before the handle() method to perform any initialization actions required. The default implementation does nothing. | python.library.socketserver#socketserver.BaseRequestHandler.setup |
class socketserver.BaseServer(server_address, RequestHandlerClass)
This is the superclass of all Server objects in the module. It defines the interface, given below, but does not implement most of the methods, which is done in subclasses. The two parameters are stored in the respective server_address and RequestHandlerClass attributes.
fileno()
Return an integer file descriptor for the socket on which the server is listening. This function is most commonly passed to selectors, to allow monitoring multiple servers in the same process.
handle_request()
Process a single request. This function calls the following methods in order: get_request(), verify_request(), and process_request(). If the user-provided handle() method of the handler class raises an exception, the server’s handle_error() method will be called. If no request is received within timeout seconds, handle_timeout() will be called and handle_request() will return.
serve_forever(poll_interval=0.5)
Handle requests until an explicit shutdown() request. Poll for shutdown every poll_interval seconds. Ignores the timeout attribute. It also calls service_actions(), which may be used by a subclass or mixin to provide actions specific to a given service. For example, the ForkingMixIn class uses service_actions() to clean up zombie child processes. Changed in version 3.3: Added service_actions call to the serve_forever method.
service_actions()
This is called in the serve_forever() loop. This method can be overridden by subclasses or mixin classes to perform actions specific to a given service, such as cleanup actions. New in version 3.3.
shutdown()
Tell the serve_forever() loop to stop and wait until it does. shutdown() must be called while serve_forever() is running in a different thread otherwise it will deadlock.
server_close()
Clean up the server. May be overridden.
address_family
The family of protocols to which the server’s socket belongs. Common examples are socket.AF_INET and socket.AF_UNIX.
RequestHandlerClass
The user-provided request handler class; an instance of this class is created for each request.
server_address
The address on which the server is listening. The format of addresses varies depending on the protocol family; see the documentation for the socket module for details. For Internet protocols, this is a tuple containing a string giving the address, and an integer port number: ('127.0.0.1', 80), for example.
socket
The socket object on which the server will listen for incoming requests.
The server classes support the following class variables:
allow_reuse_address
Whether the server will allow the reuse of an address. This defaults to False, and can be set in subclasses to change the policy.
request_queue_size
The size of the request queue. If it takes a long time to process a single request, any requests that arrive while the server is busy are placed into a queue, up to request_queue_size requests. Once the queue is full, further requests from clients will get a “Connection denied” error. The default value is usually 5, but this can be overridden by subclasses.
socket_type
The type of socket used by the server; socket.SOCK_STREAM and socket.SOCK_DGRAM are two common values.
timeout
Timeout duration, measured in seconds, or None if no timeout is desired. If handle_request() receives no incoming requests within the timeout period, the handle_timeout() method is called.
There are various server methods that can be overridden by subclasses of base server classes like TCPServer; these methods aren’t useful to external users of the server object.
finish_request(request, client_address)
Actually processes the request by instantiating RequestHandlerClass and calling its handle() method.
get_request()
Must accept a request from the socket, and return a 2-tuple containing the new socket object to be used to communicate with the client, and the client’s address.
handle_error(request, client_address)
This function is called if the handle() method of a RequestHandlerClass instance raises an exception. The default action is to print the traceback to standard error and continue handling further requests. Changed in version 3.6: Now only called for exceptions derived from the Exception class.
handle_timeout()
This function is called when the timeout attribute has been set to a value other than None and the timeout period has passed with no requests being received. The default action for forking servers is to collect the status of any child processes that have exited, while in threading servers this method does nothing.
process_request(request, client_address)
Calls finish_request() to create an instance of the RequestHandlerClass. If desired, this function can create a new process or thread to handle the request; the ForkingMixIn and ThreadingMixIn classes do this.
server_activate()
Called by the server’s constructor to activate the server. The default behavior for a TCP server just invokes listen() on the server’s socket. May be overridden.
server_bind()
Called by the server’s constructor to bind the socket to the desired address. May be overridden.
verify_request(request, client_address)
Must return a Boolean value; if the value is True, the request will be processed, and if it’s False, the request will be denied. This function can be overridden to implement access controls for a server. The default implementation always returns True.
Changed in version 3.6: Support for the context manager protocol was added. Exiting the context manager is equivalent to calling server_close(). | python.library.socketserver#socketserver.BaseServer |
address_family
The family of protocols to which the server’s socket belongs. Common examples are socket.AF_INET and socket.AF_UNIX. | python.library.socketserver#socketserver.BaseServer.address_family |
allow_reuse_address
Whether the server will allow the reuse of an address. This defaults to False, and can be set in subclasses to change the policy. | python.library.socketserver#socketserver.BaseServer.allow_reuse_address |
fileno()
Return an integer file descriptor for the socket on which the server is listening. This function is most commonly passed to selectors, to allow monitoring multiple servers in the same process. | python.library.socketserver#socketserver.BaseServer.fileno |
finish_request(request, client_address)
Actually processes the request by instantiating RequestHandlerClass and calling its handle() method. | python.library.socketserver#socketserver.BaseServer.finish_request |
get_request()
Must accept a request from the socket, and return a 2-tuple containing the new socket object to be used to communicate with the client, and the client’s address. | python.library.socketserver#socketserver.BaseServer.get_request |
handle_error(request, client_address)
This function is called if the handle() method of a RequestHandlerClass instance raises an exception. The default action is to print the traceback to standard error and continue handling further requests. Changed in version 3.6: Now only called for exceptions derived from the Exception class. | python.library.socketserver#socketserver.BaseServer.handle_error |
handle_request()
Process a single request. This function calls the following methods in order: get_request(), verify_request(), and process_request(). If the user-provided handle() method of the handler class raises an exception, the server’s handle_error() method will be called. If no request is received within timeout seconds, handle_timeout() will be called and handle_request() will return. | python.library.socketserver#socketserver.BaseServer.handle_request |
handle_timeout()
This function is called when the timeout attribute has been set to a value other than None and the timeout period has passed with no requests being received. The default action for forking servers is to collect the status of any child processes that have exited, while in threading servers this method does nothing. | python.library.socketserver#socketserver.BaseServer.handle_timeout |
process_request(request, client_address)
Calls finish_request() to create an instance of the RequestHandlerClass. If desired, this function can create a new process or thread to handle the request; the ForkingMixIn and ThreadingMixIn classes do this. | python.library.socketserver#socketserver.BaseServer.process_request |
RequestHandlerClass
The user-provided request handler class; an instance of this class is created for each request. | python.library.socketserver#socketserver.BaseServer.RequestHandlerClass |
request_queue_size
The size of the request queue. If it takes a long time to process a single request, any requests that arrive while the server is busy are placed into a queue, up to request_queue_size requests. Once the queue is full, further requests from clients will get a “Connection denied” error. The default value is usually 5, but this can be overridden by subclasses. | python.library.socketserver#socketserver.BaseServer.request_queue_size |
server_activate()
Called by the server’s constructor to activate the server. The default behavior for a TCP server just invokes listen() on the server’s socket. May be overridden. | python.library.socketserver#socketserver.BaseServer.server_activate |
server_address
The address on which the server is listening. The format of addresses varies depending on the protocol family; see the documentation for the socket module for details. For Internet protocols, this is a tuple containing a string giving the address, and an integer port number: ('127.0.0.1', 80), for example. | python.library.socketserver#socketserver.BaseServer.server_address |
server_bind()
Called by the server’s constructor to bind the socket to the desired address. May be overridden. | python.library.socketserver#socketserver.BaseServer.server_bind |
server_close()
Clean up the server. May be overridden. | python.library.socketserver#socketserver.BaseServer.server_close |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.