Teks sumber — English
Terjemahan — Bahasa Indonesia
The Python interface is a straightforward transliteration of the Unix system call and library interface for sockets to Python's object-oriented style: the :func:`~socket.socket` function returns a :dfn:`socket object` whose methods implement the various socket system calls. Parameter types are somewhat higher-level than in the C interface: as with :meth:`read` and :meth:`write` operations on Python files, buffer allocation on receive operations is automatic, and buffer length is implicit on send operations.
A TLS/SSL wrapper for socket objects.
The address format required by a particular socket object is automatically selected based on the address family specified when the socket object was created. Socket addresses are represented as follows:
The address of an :const:`AF_UNIX` socket bound to a file system node is represented as a string, using the file system encoding and the ``'surrogateescape'`` error handler (see :pep:`383`). An address in Linux's abstract namespace is returned as a :term:`bytes-like object` with an initial null byte; note that sockets in this namespace can communicate with normal file system sockets, so programs intended to run on Linux may need to deal with both types of address. A string or bytes-like object can be used for either type of address when passing it as an argument.
Writable :term:`bytes-like object` is now accepted.
:const:`BTPROTO_SCO` accepts ``bdaddr`` where ``bdaddr`` is the Bluetooth address as a string or a :class:`bytes` object. (ex. ``'12:23:34:45:56:67'`` or ``b'12:23:34:45:56:67'``)
*addr* - Optional bytes-like object specifying the hardware physical address, whose interpretation depends on the device.
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 :meth:`~socket.setsockopt` and :meth:`~socket.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.
Constants for Windows' WSAIoctl(). The constants are used as arguments to the :meth:`~socket.socket.ioctl` method of socket objects.
Used in the level argument to the :meth:`~socket.setsockopt` and :meth:`~socket.getsockopt` methods of Bluetooth socket objects.
Used in the option name and value argument to the :meth:`~socket.setsockopt` and :meth:`~socket.getsockopt` methods of Bluetooth socket objects.
These constants are used by the :meth:`~socket.socket.shutdown` method of socket objects.
The following functions all create :ref:`socket objects <socket-objects>`.
The :class:`socket <socket.socket>` class constructor creates a new socket directly; see :ref:`socket-objects` for its parameters and full description.
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 :func:`~socket.socket` function. The default family is :const:`AF_UNIX` if defined on the platform; otherwise, the default is :const:`AF_INET`.
The returned socket objects now support the whole socket API, rather than a subset.
Connect to a TCP service listening on the internet *address* (a 2-tuple ``(host, port)``), and return the socket object. This is a higher-level function than :meth:`socket.connect`: if *host* is a non-numeric hostname, it will try to resolve it for both :data:`AF_INET` and :data:`AF_INET6`, and then try to connect to all possible addresses in turn until a connection succeeds. This makes it easy to write clients that are compatible to both IPv4 and IPv6.
Convenience function which creates a TCP socket bound to *address* (a 2-tuple ``(host, port)``) and returns the socket object.
Duplicate the file descriptor *fd* (an integer as returned by a file object's :meth:`~io.IOBase.fileno` method) and build a socket object from the result. Address family, socket type and protocol number are as for the :func:`~socket.socket` function. The file descriptor should refer to a socket, but this is not checked --- subsequent operations on the object may fail if the file descriptor is invalid. This function is rarely needed, but can be used to get or set socket options on a socket passed to a program as standard input or output (such as a server started by the Unix inet daemon). The socket is assumed to be in blocking mode.
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 :c:struct:`in_addr`, which is the C type for the 32-bit packed binary this function returns.
Convert a 32-bit packed IPv4 address (a :term:`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 :c:struct:`in_addr`, which is the C type for the 32-bit packed binary data this function takes as an argument.
Convert an IP address from its family-specific string format to a packed, binary format. :func:`inet_pton` is useful when a library or network protocol calls for an object of type :c:struct:`in_addr` (similar to :func:`inet_aton`) or :c:struct:`in6_addr`.
Convert a packed IP address (a :term:`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'``). :func:`inet_ntop` is useful when a library or network protocol returns an object of type :c:struct:`in_addr` (similar to :func:`inet_ntoa`) or :c:struct:`in6_addr`.
Supported values for *address_family* are currently :const:`AF_INET` and :const:`AF_INET6`. If the bytes object *packed_ip* is not the correct length for the specified address family, :exc:`ValueError` will be raised. :exc:`OSError` is raised for errors from the call to :func:`inet_ntop`.
Return the default timeout in seconds (float) for new socket objects. A value of ``None`` indicates that new socket objects have no timeout. When the socket module is first imported, the default is ``None``.
Set the default timeout in seconds (real number) for new socket objects. When the socket module is first imported, the default is ``None``. See :meth:`~socket.settimeout` for possible values and their respective meanings.
Socket Objects
Socket objects have the following methods. Except for :meth:`~socket.makefile`, these correspond to Unix system calls applicable to sockets.
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.
Mark the socket closed. The underlying system resource (e.g. a file descriptor) is also closed when all file objects from :meth:`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).
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.
Return the value of the given socket option (see the Unix man page :manpage:`getsockopt(2)`). The needed symbolic constants (:ref:`SO_\* etc. <socket-unix-constants>`) 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 :mod:`struct` for a way to decode C structures encoded as byte strings).
On other platforms, the generic :func:`fcntl.fcntl` and :func:`fcntl.ioctl` functions may be used; they accept a socket object as their first argument.
Return a :term:`file object` associated with the socket. The exact returned type depends on the arguments given to :meth:`makefile`. These arguments are interpreted the same way as by the built-in :func:`open` function, except the only supported *mode* values are ``'r'`` (default), ``'w'``, ``'b'``, or a combination of those.
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 :meth:`makefile` won't close the original socket unless all other file objects have been closed and :meth:`~socket.socket.close` has been called on the socket object.
On Windows, the file-like object created by :meth:`makefile` cannot be used where a file object with a file descriptor is expected, such as the stream arguments of :meth:`subprocess.Popen`.
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*. A returned empty bytes object indicates that the client has disconnected. See the Unix manual page :manpage:`recv(2)` for the meaning of the optional argument *flags*; it defaults to zero.
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 :manpage:`recv(2)` for the meaning of the optional argument *flags*; it defaults to zero. The format of *address* depends on the address family --- see :ref:`socket-addresses`.
The return value is a 4-tuple: ``(data, ancdata, msg_flags, address)``. The *data* item is a :class:`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 :class:`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, :meth:`sendmsg` and :meth:`recvmsg` can be used to pass file descriptors between processes over an :const:`AF_UNIX` socket. When this facility is used (it is often restricted to :const:`SOCK_STREAM` sockets), :meth:`recvmsg` will return, in its ancillary data, items of the form ``(socket.SOL_SOCKET, socket.SCM_RIGHTS, fds)``, where *fds* is a :class:`bytes` object representing the new file descriptors as a binary array of the native C :c:expr:`int` type. If :meth:`recvmsg` raises an exception after the system call returns, it will first attempt to close any file descriptors received via this mechanism.
Receive normal data and ancillary data from the socket, behaving as :meth:`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. :class:`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 (:func:`~os.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 :meth:`recvmsg`.
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 :term:`bytes-like objects <bytes-like object>` (e.g. :class:`bytes` objects); the operating system may set a limit (:func:`~os.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 :func:`CMSG_SPACE`) might support sending only one control message per call. The *flags* argument defaults to 0 and has the same meaning as for :meth:`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.
Send a file until EOF is reached by using high-performance :mod:`os.sendfile` and return the total number of bytes which were sent. *file* must be a regular file object opened in binary mode. If :mod:`os.sendfile` is not available (e.g. Windows) or *file* is not a regular file :meth:`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 :meth:`file.tell() <io.IOBase.tell>` can be used to figure out the number of bytes which were sent. The socket must be of :const:`SOCK_STREAM` type. Non-blocking sockets are not supported.
Set the value of the given socket option (see the Unix manual page :manpage:`setsockopt(2)`). The needed symbolic constants are defined in this module (:ref:`!SO_\* etc. <socket-unix-constants>`). The value can be an integer, ``None`` or a :term:`bytes-like object` representing a buffer. In the latter case it is up to the caller to ensure that the bytestring contains the proper bits (see the optional built-in module :mod:`struct` for a way to encode C structures as bytestrings). When *value* is set to ``None``, *optlen* argument is required. It's equivalent to calling :c:func:`!setsockopt` C function with ``optval=NULL`` and ``optlen=optlen``.
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 :func:`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.
Socket objects also have these (read-only) attributes that correspond to the values given to the :class:`~socket.socket` constructor.
A socket object can be in one of three modes: blocking, non-blocking, or timeout. Sockets are by default always created in blocking mode, but this can be changed by calling :func:`setdefaulttimeout`.
At the operating system level, sockets in *timeout mode* are internally set in non-blocking mode. Also, the blocking and timeout modes are shared between file descriptors and socket objects that refer to the same network endpoint. This implementation detail can have visible consequences if e.g. you decide to use the :meth:`~socket.fileno` of a socket.
After binding (:const:`CAN_RAW`) or connecting (:const:`CAN_BCM`) the socket, you can use the :meth:`socket.send` and :meth:`socket.recv` operations (and their counterparts) on the socket object as usual.
object
objek