Lines Matching full:socket
1 :mod:`socket` --- Low-level networking interface
4 .. module:: socket
7 **Source code:** :source:`Lib/socket.py`
11 This module provides access to the BSD *socket* interface. It is available on
17 system socket APIs.
22 .. index:: pair: object; socket
26 :func:`.socket` function returns a :dfn:`socket object` whose methods implement
27 the various socket system calls. Parameter types are somewhat higher-level than
39 A TLS/SSL wrapper for socket objects.
42 Socket families
45 Depending on the system and the build options, various socket families
48 The address format required by a particular socket object is automatically
49 selected based on the address family specified when the socket object was
50 created. Socket addresses are represented as follows:
52 - The address of an :const:`AF_UNIX` socket bound to a file system node
63 Previously, :const:`AF_UNIX` socket paths were assumed to use UTF-8
86 :mod:`socket` module methods, *flowinfo* and *scope_id* can be omitted just for
159 - :const:`AF_ALG` is a Linux-only socket based interface to Kernel
160 cryptography. An algorithm socket is configured with a tuple of two to four
202 looped back to a packet socket.
209 - :const:`AF_QIPCRTR` is a Linux-only socket based interface for communicating
219 what portion of a packet is covered with the checksum. It adds two socket
227 Such a socket should be constructed with
228 ``socket(AF_INET, SOCK_DGRAM, IPPROTO_UDPLITE)`` for IPv4 or
229 ``socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDPLITE)`` for IPv6.
235 If you use a hostname in the *host* portion of IPv4/v6 socket address, the
237 returned from the DNS resolution. The socket address will be resolved
244 related to socket or address semantics raise :exc:`OSError` or one of its
247 Non-blocking mode is supported through :meth:`~socket.setblocking`. A
249 :meth:`~socket.settimeout`.
255 The module :mod:`socket` exports the following elements.
300 occurs on a socket which has had timeouts enabled via a prior call to
301 :meth:`~socket.settimeout` (or implicitly through
302 :func:`~socket.setdefaulttimeout`). The accompanying value is a string
325 first argument to :func:`.socket`. If the :const:`AF_UNIX` constant is not
336 These constants represent the socket types, used for the second argument to
337 :func:`.socket`. More constants may be available depending on the system.
344 These two constants, if defined, can be combined with the socket types and
373 and/or the IP protocol, are also defined in the socket module. They are
375 methods of socket objects. In most cases, only those symbols that are defined
408 also defined in the socket module.
422 defined in the socket module.
433 Enables CAN FD support in a CAN_RAW socket. This is disabled by default.
435 you must accept both CAN and CAN FD frames when reading from the socket.
478 also defined in the socket module.
489 also defined in the socket module.
502 :meth:`~socket.socket.ioctl` method of socket objects.
510 TIPC related constants, matching the ones exported by the C socket API. See
551 any address when specifying the binding socket with
600 The following functions all create :ref:`socket objects <socket-objects>`.
603 .. class:: socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None)
605 Create a new socket using the given address family, socket type and protocol
608 or :const:`AF_RDS`. The socket type should be :const:`SOCK_STREAM` (the
619 of :meth:`socket.getpeername` but not the actual OS resource. Unlike
620 :func:`socket.fromfd`, *fileno* will return the same socket and not a
621 duplicate. This may help close a detached socket using
622 :meth:`socket.close()`.
624 The newly created socket is :ref:`non-inheritable <fd_inheritance>`.
626 .. audit-event:: socket.__new__ self,family,type,protocol socket.socket
636 The returned socket is now non-inheritable.
644 :attr:`socket.type` will not reflect them. They are still passed
645 to the underlying system ``socket()`` call. Therefore,
649 sock = socket.socket(
650 socket.AF_INET,
651 socket.SOCK_STREAM | socket.SOCK_NONBLOCK)
653 will still create a non-blocking socket on OSes that support
655 ``socket.SOCK_STREAM``.
665 Build a pair of connected socket objects using the given address family, socket
666 type, and protocol number. Address family, socket type, and protocol number are
667 as for the :func:`.socket` function above. The default family is :const:`AF_UNIX`
673 The returned socket objects now support the whole socket API, rather
686 ``(host, port)``), and return the socket object. This is a higher-level
687 function than :meth:`socket.connect`: if *host* is a non-numeric hostname,
694 socket instance before attempting to connect. If no *timeout* is
699 socket to bind to as its source address before connecting. If host or port
716 Convenience function which creates a TCP socket bound to *address* (a 2-tuple
717 ``(host, port)``) and return the socket object.
720 *backlog* is the queue size passed to :meth:`socket.listen`; if not specified
722 *reuse_port* dictates whether to set the :data:`SO_REUSEPORT` socket option.
724 If *dualstack_ipv6* is true and the platform supports it the socket will
729 :meth:`socket.getpeername` when an IPv4 connection occurs will be an IPv6
737 import socket
740 if socket.has_dualstack_ipv6():
741 s = socket.create_server(addr, family=socket.AF_INET6, dualstack_ipv6=True)
743 s = socket.create_server(addr)
746 On POSIX platforms the :data:`SO_REUSEADDR` socket option is set in order to
754 Return ``True`` if the platform supports creating a TCP socket which can
762 :meth:`fileno` method) and build a socket object from the result. Address
763 family, socket type and protocol number are as for the :func:`.socket` function
764 above. The file descriptor should refer to a socket, but this is not checked ---
766 This function is rarely needed, but can be used to get or set socket options on
767 a socket passed to a program as standard input or output (such as a server
768 started by the Unix inet daemon). The socket is assumed to be in blocking mode.
770 The newly created socket is :ref:`non-inheritable <fd_inheritance>`.
773 The returned socket is now non-inheritable.
778 Instantiate a socket from data obtained from the :meth:`socket.share`
779 method. The socket is assumed to be in blocking mode.
788 This is a Python type object that represents the socket object type. It is the
789 same as ``type(socket(...))``.
795 The :mod:`socket` module also offers various network-related services:
800 Close a socket file descriptor. This is like :func:`os.close`, but for
802 does not work for socket file descriptors.
809 all the necessary arguments for creating a socket connected to that service.
828 meant to be passed to the :func:`.socket` function. *canonname* will be
831 will be empty. *sockaddr* is a tuple describing a socket address, whose
834 :const:`AF_INET6`), and is meant to be passed to the :meth:`socket.connect`
837 .. audit-event:: socket.getaddrinfo host,port,family,type,protocol socket.getaddrinfo
843 >>> socket.getaddrinfo("example.org", 80, proto=socket.IPPROTO_TCP)
844 [(socket.AF_INET6, socket.SOCK_STREAM,
846 (socket.AF_INET, socket.SOCK_STREAM,
875 .. audit-event:: socket.gethostbyname hostname socket.gethostbyname
891 .. audit-event:: socket.gethostbyname hostname socket.gethostbyname_ex
901 .. audit-event:: socket.gethostname "" socket.gethostname
919 .. audit-event:: socket.gethostbyaddr ip_address socket.gethostbyaddr
926 Translate a socket address *sockaddr* into a 2-tuple ``(host, port)``. Depending
936 .. audit-event:: socket.getnameinfo sockaddr socket.getnameinfo
944 suitable for passing as the (optional) third argument to the :func:`.socket`
946 (:const:`SOCK_RAW`); for the normal socket modes, the correct protocol is chosen
958 .. audit-event:: socket.getservbyname servicename,protocolname socket.getservbyname
969 .. audit-event:: socket.getservbyport port,protocolname socket.getservbyport
1099 can often be used as the buffer size for :meth:`~socket.recvmsg` to
1115 Return the buffer size needed for :meth:`~socket.recvmsg` to
1138 Return the default timeout in seconds (float) for new socket objects. A value
1139 of ``None`` indicates that new socket objects have no timeout. When the socket
1145 Set the default timeout in seconds (float) for new socket objects. When
1146 the socket module is first imported, the default is ``None``. See
1147 :meth:`~socket.settimeout` for possible values and their respective
1156 .. audit-event:: socket.sethostname name socket.sethostname
1226 Send the list of file descriptors *fds* over an :const:`AF_UNIX` socket *sock*.
1232 Unix platforms supporting :meth:`~socket.sendmsg`
1240 Receive up to *maxfds* file descriptors from an :const:`AF_UNIX` socket *sock*.
1246 Unix platforms supporting :meth:`~socket.sendmsg`
1258 Socket Objects
1261 Socket objects have the following methods. Except for
1262 :meth:`~socket.makefile`, these correspond to Unix system calls applicable
1267 context manager is equivalent to calling :meth:`~socket.close`.
1270 .. method:: socket.accept()
1272 Accept a connection. The socket must be bound to an address and listening for
1274 *new* socket object usable to send and receive data on the connection, and
1275 *address* is the address bound to the socket on the other end of the connection.
1277 The newly created socket is :ref:`non-inheritable <fd_inheritance>`.
1280 The socket is now non-inheritable.
1288 .. method:: socket.bind(address)
1290 Bind the socket to *address*. The socket must not already be bound. (The format
1293 .. audit-event:: socket.bind self,address socket.socket.bind
1298 .. method:: socket.close()
1300 Mark the socket closed. The underlying system resource (e.g. a file
1302 are closed. Once that happens, all future operations on the socket
1322 .. method:: socket.connect(address)
1324 Connect to a remote socket at *address*. (The format of *address* depends on the
1329 signal handler doesn't raise an exception and the socket is blocking or has
1334 .. audit-event:: socket.connect self,address socket.socket.connect
1339 signal, the signal handler doesn't raise an exception and the socket is
1345 .. method:: socket.connect_ex(address)
1354 .. audit-event:: socket.connect self,address socket.socket.connect_ex
1358 .. method:: socket.detach()
1360 Put the socket object into closed state without actually closing the
1367 .. method:: socket.dup()
1369 Duplicate the socket.
1371 The newly created socket is :ref:`non-inheritable <fd_inheritance>`.
1374 The socket is now non-inheritable.
1379 .. method:: socket.fileno()
1381 Return the socket's file descriptor (a small integer), or -1 on failure. This
1388 .. method:: socket.get_inheritable()
1390 Get the :ref:`inheritable flag <fd_inheritance>` of the socket's file
1391 descriptor or socket's handle: ``True`` if the socket can be inherited in
1397 .. method:: socket.getpeername()
1399 Return the remote address to which the socket is connected. This is useful to
1400 find out the port number of a remote IPv4/v6 socket, for instance. (The format
1405 .. method:: socket.getsockname()
1407 Return the socket's own address. This is useful to find out the port number of
1408 an IPv4/v6 socket, for instance. (The format of the address returned depends on
1412 .. method:: socket.getsockopt(level, optname[, buflen])
1414 Return the value of the given socket option (see the Unix man page
1426 .. method:: socket.getblocking()
1428 Return ``True`` if socket is in blocking mode, ``False`` if in
1431 This is equivalent to checking ``socket.gettimeout() != 0``.
1436 .. method:: socket.gettimeout()
1438 Return the timeout in seconds (float) associated with socket operations,
1443 .. method:: socket.ioctl(control, option)
1453 functions may be used; they accept a socket object as their first argument.
1461 .. method:: socket.listen([backlog])
1474 .. method:: socket.makefile(mode='r', buffering=None, *, encoding=None, \
1479 Return a :term:`file object` associated with the socket. The exact returned
1484 The socket must be in blocking mode; it can have a timeout, but the file
1489 original socket unless all other file objects have been closed and
1490 :meth:`socket.close` has been called on the socket object.
1499 .. method:: socket.recv(bufsize[, flags])
1501 Receive data from the socket. The return value is a bytes object representing the
1517 .. method:: socket.recvfrom(bufsize[, flags])
1519 Receive data from the socket. The return value is a pair ``(bytes, address)``
1521 address of the socket sending the data. See the Unix manual page
1535 .. method:: socket.recvmsg(bufsize[, ancbufsize[, flags]])
1538 the socket. The *ancbufsize* argument sets the size in bytes of
1557 If the receiving socket is unconnected, *address* is the address of
1558 the sending socket, if available; otherwise, its value is
1563 socket. When this facility is used (it is often restricted to
1565 ancillary data, items of the form ``(socket.SOL_SOCKET,
1566 socket.SCM_RIGHTS, fds)``, where *fds* is a :class:`bytes` object
1585 import socket, array
1589 msg, ancdata, flags, addr = sock.recvmsg(msglen, socket.CMSG_LEN(maxfds * fds.itemsize))
1591 if cmsg_level == socket.SOL_SOCKET and cmsg_type == socket.SCM_RIGHTS:
1608 .. method:: socket.recvmsg_into(buffers[, ancbufsize[, flags]])
1610 Receive normal data and ancillary data from the socket, behaving as
1628 >>> import socket
1629 >>> s1, s2 = socket.socketpair()
1647 .. method:: socket.recvfrom_into(buffer[, nbytes[, flags]])
1649 Receive data from the socket, writing it into *buffer* instead of creating a
1651 the number of bytes received and *address* is the address of the socket sending
1657 .. method:: socket.recv_into(buffer[, nbytes[, flags]])
1659 Receive up to *nbytes* bytes from the socket, storing the data into a buffer
1666 .. method:: socket.send(bytes[, flags])
1668 Send data to the socket. The socket must be connected to a remote socket. The
1673 information on this topic, consult the :ref:`socket-howto`.
1681 .. method:: socket.sendall(bytes[, flags])
1683 Send data to the socket. The socket must be connected to a remote socket. The
1691 The socket timeout is no longer reset each time data is sent successfully.
1692 The socket timeout is now the maximum total duration to send all data.
1700 .. method:: socket.sendto(bytes, address)
1701 socket.sendto(bytes, flags, address)
1703 Send data to the socket. The socket should not be connected to a remote socket,
1704 since the destination socket is specified by *address*. The optional *flags*
1709 .. audit-event:: socket.sendto self,address socket.socket.sendto
1717 .. method:: socket.sendmsg(buffers[, ancdata[, flags[, address]]])
1719 Send normal and ancillary data to the socket, gathering the
1740 over an :const:`AF_UNIX` socket, on systems which support the
1743 import socket, array
1746 … return sock.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", fds))])
1752 .. audit-event:: socket.sendmsg self,address socket.socket.sendmsg
1761 .. method:: socket.sendmsg_afalg([msg], *, op[, iv[, assoclen[, flags]]])
1763 Specialized version of :meth:`~socket.sendmsg` for :const:`AF_ALG` socket.
1764 Set mode, IV, AEAD associated data length and flags for :const:`AF_ALG` socket.
1770 .. method:: socket.sendfile(file, offset=0, count=None)
1781 bytes which were sent. The socket must be of :const:`SOCK_STREAM` type.
1786 .. method:: socket.set_inheritable(inheritable)
1788 Set the :ref:`inheritable flag <fd_inheritance>` of the socket's file
1789 descriptor or socket's handle.
1794 .. method:: socket.setblocking(flag)
1796 Set blocking or non-blocking mode of the socket: if *flag* is false, the
1797 socket is set to non-blocking, else to blocking mode.
1799 This method is a shorthand for certain :meth:`~socket.settimeout` calls:
1807 :attr:`socket.type`.
1810 .. method:: socket.settimeout(value)
1812 Set a timeout on blocking socket operations. The *value* argument can be a
1814 If a non-zero value is given, subsequent socket operations will raise a
1816 the operation has completed. If zero is given, the socket is put in
1817 non-blocking mode. If ``None`` is given, the socket is put in blocking mode.
1819 For further information, please consult the :ref:`notes on socket timeouts <socket-timeouts>`.
1823 :attr:`socket.type`.
1826 .. method:: socket.setsockopt(level, optname, value: int)
1827 .. method:: socket.setsockopt(level, optname, value: buffer)
1829 .. method:: socket.setsockopt(level, optname, None, optlen: int)
1834 Set the value of the given socket option (see the Unix manual page
1836 :mod:`socket` module (:const:`SO_\*` etc.). The value can be an integer,
1853 .. method:: socket.shutdown(how)
1863 .. method:: socket.share(process_id)
1865 Duplicate a socket and prepare it for sharing with a target process. The
1868 communication and the socket can be recreated there using :func:`fromshare`.
1869 Once this method has been called, it is safe to close the socket since
1878 :meth:`~socket.recv` and :meth:`~socket.send` without *flags* argument instead.
1880 Socket objects also have these (read-only) attributes that correspond to the
1881 values given to the :class:`~socket.socket` constructor.
1884 .. attribute:: socket.family
1886 The socket family.
1889 .. attribute:: socket.type
1891 The socket type.
1894 .. attribute:: socket.proto
1896 The socket protocol.
1902 Notes on socket timeouts
1905 A socket object can be in one of three modes: blocking, non-blocking, or
1914 :mod:`select` module can be used to know when and whether a socket is available
1918 timeout specified for the socket (they raise a :exc:`timeout` exception)
1924 file descriptors and socket objects that refer to the same network endpoint.
1926 to use the :meth:`~socket.fileno()` of a socket.
1931 The :meth:`~socket.connect` operation is also subject to the timeout
1932 setting, and in general it is recommended to call :meth:`~socket.settimeout`
1933 before calling :meth:`~socket.connect` or pass a timeout parameter to
1935 return a connection timeout error of its own regardless of any Python socket
1942 the :meth:`~socket.accept` method inherit that timeout. Otherwise, the
1943 behaviour depends on settings of the listening socket:
1945 * if the listening socket is in *blocking mode* or in *timeout mode*,
1946 the socket returned by :meth:`~socket.accept` is in *blocking mode*;
1948 * if the listening socket is in *non-blocking mode*, whether the socket
1949 returned by :meth:`~socket.accept` is in blocking or non-blocking mode
1961 using it. Note that a server must perform the sequence :func:`.socket`,
1962 :meth:`~socket.bind`, :meth:`~socket.listen`, :meth:`~socket.accept` (possibly
1963 repeating the :meth:`~socket.accept` to service more than one client), while a
1964 client only needs the sequence :func:`.socket`, :meth:`~socket.connect`. Also
1965 note that the server does not :meth:`~socket.sendall`/:meth:`~socket.recv` on
1966 the socket it is listening on but on the new socket returned by
1967 :meth:`~socket.accept`.
1972 import socket
1976 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
1990 import socket
1994 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
2008 import socket
2014 for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,
2015 socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
2018 s = socket.socket(af, socktype, proto)
2031 print('could not open socket')
2044 import socket
2050 for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
2053 s = socket.socket(af, socktype, proto)
2065 print('could not open socket')
2076 import socket
2079 HOST = socket.gethostbyname(socket.gethostname())
2081 # create a raw socket and bind it to the public interface
2082 s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
2086 s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
2089 s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
2095 s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
2097 The next example shows how to use the socket interface to communicate to a CAN
2098 network using the raw socket protocol. To use CAN with the broadcast
2099 manager protocol instead, open a socket with::
2101 socket.socket(socket.AF_CAN, socket.SOCK_DGRAM, socket.CAN_BCM)
2103 After binding (:const:`CAN_RAW`) or connecting (:const:`CAN_BCM`) the socket, you
2104 can use the :meth:`socket.send` and :meth:`socket.recv` operations (and
2105 their counterparts) on the socket object as usual.
2109 import socket
2128 # create a raw socket and bind it to the 'vcan0' interface
2129 s = socket.socket(socket.AF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
2152 This is because the previous execution has left the socket in a ``TIME_WAIT``
2155 There is a :mod:`socket` flag to set, in order to prevent this,
2156 :data:`socket.SO_REUSEADDR`::
2158 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
2159 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2162 the :data:`SO_REUSEADDR` flag tells the kernel to reuse a local socket in
2168 For an introduction to socket programming (in C), see the following papers:
2177 socket-related system calls are also a valuable source of information on the
2178 details of socket semantics. For Unix, refer to the manual pages; for Windows,
2180 want to refer to :rfc:`3493` titled Basic Socket Interface Extensions for IPv6.