The address format required by a particular socket object is automaticallyselected based on the address family specified when the socket object wascreated. Socket addresses are represented as follows:
For AF_INET6 address family, a four-tuple (host, port, flowinfo,scope_id) is used, where flowinfo and scope_id represent the sin6_flowinfoand sin6_scope_id members in struct sockaddr_in6 in C. Forsocket module methods, flowinfo and scope_id can be omitted just forbackward compatibility. Note, however, omission of scope_id can cause problemsin manipulating scoped IPv6 addresses.
AF_QIPCRTR is a Linux-only socket based interface for communicatingwith services running on co-processors in Qualcomm platforms. The addressfamily is represented as a (node, port) tuple where the node and portare non-negative integers.
IPPROTO_UDPLITE is a variant of UDP which allows you to specifywhat portion of a packet is covered with the checksum. It adds two socketoptions that you can change.self.setsockopt(IPPROTO_UDPLITE, UDPLITE_SEND_CSCOV, length) willchange what portion of outgoing packets are covered by the checksum andself.setsockopt(IPPROTO_UDPLITE, UDPLITE_RECV_CSCOV, length) willfilter out packets which cover too little of their data. In both caseslength should be in range(8, 2**16, 8).
AF_HYPERV is a Windows-only socket based interface for communicatingwith Hyper-V hosts and guests. The address family is represented as a(vm_id, service_id) tuple where the vm_id and service_id areUUID strings.
If you use a hostname in the host portion of IPv4/v6 socket address, theprogram may show a nondeterministic behavior, as Python uses the first addressreturned from the DNS resolution. The socket address will be resolveddifferently into an actual IPv4/v6 address, depending on the results from DNSresolution and/or the host configuration. For deterministic behavior use anumeric address in host portion.
All errors raise exceptions. The normal exceptions for invalid argument typesand out-of-memory conditions can be raised. Errorsrelated to socket or address semantics raise OSError or one of itssubclasses.
These constants represent the address (and protocol) families, used for thefirst argument to socket(). If the AF_UNIX constant is notdefined then this protocol is unsupported. More constants may be availabledepending on the system.
These constants represent the socket types, used for the second argument tosocket(). More constants may be available depending on the system.(Only SOCK_STREAM and SOCK_DGRAM appear to be generallyuseful.)
Many constants of these forms, documented in the Unix documentation on socketsand/or the IP protocol, are also defined in the socket module. They aregenerally used in arguments to the setsockopt() and getsockopt()methods of socket objects. In most cases, only those symbols that are definedin the Unix header files are defined; for a few symbols, default values areprovided.
Enables CAN FD support in a CAN_RAW socket. This is disabled by default.This allows your application to send both CAN and CAN FD frames; however,you must accept both CAN and CAN FD frames when reading from the socket.
LOCAL_CREDS and LOCAL_CREDS_PERSISTENT can be usedwith SOCK_DGRAM, SOCK_STREAM sockets, equivalent toLinux/DragonFlyBSD SO_PASSCRED, while LOCAL_CREDSsends the credentials at first read, LOCAL_CREDS_PERSISTENTsends for each read, SCM_CREDS2 must be then used forthe latter for the message type.
Create a new socket using the given address family, socket type and protocolnumber. 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 (thedefault), SOCK_DGRAM, SOCK_RAW or perhaps one of the otherSOCK_ constants. The protocol number is usually zero and may be omittedor in the case where the address family is AF_CAN the protocolshould be one of CAN_RAW, CAN_BCM, CAN_ISOTP orCAN_J1939.
If fileno is specified, the values for family, type, and proto areauto-detected from the specified file descriptor. Auto-detection can beoverruled by calling the function with explicit family, type, or protoarguments. This only affects how Python represents e.g. the return valueof socket.getpeername() but not the actual OS resource. Unlikesocket.fromfd(), fileno will return the same socket and not aduplicate. This may help close a detached socket usingsocket.close().
Changed in version 3.7: When SOCK_NONBLOCK or SOCK_CLOEXECbit flags are applied to type they are cleared, andsocket.type will not reflect them. They are still passedto the underlying system socket() call. Therefore,
Build a pair of connected socket objects using the given address family, sockettype, and protocol number. Address family, socket type, and protocol number areas for the socket() function above. The default family is AF_UNIXif defined on the platform; otherwise, the default is AF_INET.
Connect to a TCP service listening on the internet address (a 2-tuple(host, port)), and return the socket object. This is a higher-levelfunction than socket.connect(): if host is a non-numeric hostname,it will try to resolve it for both AF_INET and AF_INET6,and then try to connect to all possible addresses in turn until aconnection succeeds. This makes it easy to write clients that arecompatible to both IPv4 and IPv6.
Passing the optional timeout parameter will set the timeout on thesocket instance before attempting to connect. If no timeout issupplied, the global default timeout setting returned bygetdefaulttimeout() is used.
family should be either AF_INET or AF_INET6.backlog is the queue size passed to socket.listen(); if not specified, a default reasonable value is chosen.reuse_port dictates whether to set the SO_REUSEPORT socket option.
If dualstack_ipv6 is true and the platform supports it the socket willbe able to accept both IPv4 and IPv6 connections, else it will raiseValueError. Most POSIX platforms and Windows are supposed to supportthis functionality.When this functionality is enabled the address returned bysocket.getpeername() when an IPv4 connection occurs will be an IPv6address represented as an IPv4-mapped IPv6 address.If dualstack_ipv6 is false it will explicitly disable this functionalityon platforms that enable it by default (e.g. Linux).This parameter can be used in conjunction with has_dualstack_ipv6():
Translate the host/port argument into a sequence of 5-tuples that containall the necessary arguments for creating a socket connected to that service.host is a domain name, a string representation of an IPv4/v6 addressor None. port is a string service name such as 'http', a numericport number or None. By passing None as the value of hostand port, you can pass NULL to the underlying C API.
In these tuples, family, type, proto are all integers and aremeant to be passed to the socket() function. canonname will bea string representing the canonical name of the host ifAI_CANONNAME is part of the flags argument; else canonnamewill be empty. sockaddr is a tuple describing a socket address, whoseformat depends on the returned family (a (address, port) 2-tuple forAF_INET, a (address, port, flowinfo, scope_id) 4-tuple forAF_INET6), and is meant to be passed to the socket.connect()method.
Translate a socket address sockaddr into a 2-tuple (host, port). Dependingon the settings of flags, the result can contain a fully qualified domain nameor numeric address representation in host. Similarly, port can contain astring port name or a numeric port number.
Accept a connection. The socket must be bound to an address and listening forconnections. The return value is a pair (conn, address) where conn is anew socket object usable to send and receive data on the connection, andaddress 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 filedescriptor) is also closed when all file objects from makefile()are closed. Once that happens, all future operations on the socketobject will fail. The remote end will receive no more data (afterqueued data is flushed).
Return the value of the given socket option (see the Unix man pagegetsockopt(2)). The needed symbolic constants (SO_* etc.)are defined in this module. If buflen is absent, an integer option is assumedand its integer value is returned by the function. If buflen is present, itspecifies the maximum length of the buffer used to receive the option in, andthis buffer is returned as a bytes object. It is up to the caller to decode thecontents of the buffer (see the optional built-in module struct for a wayto decode C structures encoded as byte strings).
Receive data from the socket. The return value is a bytes object representing thedata received. The maximum amount of data to be received at once is specifiedby bufsize. See the Unix manual page recv(2) for the meaning ofthe optional argument flags; it defaults to zero.
Receive normal data (up to bufsize bytes) and ancillary data fromthe socket. The ancbufsize argument sets the size in bytes ofthe internal buffer used to receive the ancillary data; it defaultsto 0, meaning that no ancillary data will be received. Appropriatebuffer sizes for ancillary data can be calculated usingCMSG_SPACE() or CMSG_LEN(), and items which do not fitinto the buffer might be truncated or discarded. The flagsargument defaults to 0 and has the same meaning as forrecv().
The return value is a 4-tuple: (data, ancdata, msg_flags,address). The data item is a bytes object holding thenon-ancillary data received. The ancdata item is a list of zeroor more tuples (cmsg_level, cmsg_type, cmsg_data) representingthe ancillary data (control messages) received: cmsg_level andcmsg_type are integers specifying the protocol level andprotocol-specific type respectively, and cmsg_data is abytes object holding the associated data. The msg_flagsitem is the bitwise OR of various flags indicating conditions onthe received message; see your system documentation for details.If the receiving socket is unconnected, address is the address ofthe sending socket, if available; otherwise, its value isunspecified.
e2b47a7662