cinap_lenrekadd hg and python4bb9e2215 years agoHistory
910 lines · 36.6 KB · TeX
RawDownload
\section{\module{socket} ---         Low-level networking interface} \declaremodule{builtin}{socket}\modulesynopsis{Low-level networking interface.}  This module provides access to the BSD \emph{socket} interface.It is available on all modern \UNIX{} systems, Windows, MacOS, BeOS,OS/2, and probably additional platforms.  \note{Some behavior may beplatform dependent, since calls are made to the operating system socket APIs.} For an introduction to socket programming (in C), see the followingpapers: \citetitle{An Introductory 4.3BSD Interprocess CommunicationTutorial}, by Stuart Sechrest and \citetitle{An Advanced 4.3BSDInterprocess Communication Tutorial}, by Samuel J.  Leffler et al,both in the \citetitle{\UNIX{} Programmer's Manual, Supplementary Documents 1}(sections PS1:7 and PS1:8).  The platform-specific reference materialfor the various socket-related system calls are also a valuable sourceof information on the details of socket semantics.  For \UNIX, referto the manual pages; for Windows, see the WinSock (or Winsock 2)specification.For IPv6-ready APIs, readers may want to refer to \rfc{2553} titled\citetitle{Basic Socket Interface Extensions for IPv6}. The Python interface is a straightforward transliteration of the\UNIX{} system call and library interface for sockets to Python'sobject-oriented style: the \function{socket()} function returns a\dfn{socket object}\obindex{socket} whose methods implement thevarious socket system calls.  Parameter types are somewhathigher-level than in the C interface: as with \method{read()} and\method{write()} operations on Python files, buffer allocation onreceive operations is automatic, and buffer length is implicit on sendoperations. Socket addresses are represented as follows:A single string is used for the \constant{AF_UNIX} address family.A pair \code{(\var{host}, \var{port})} is used for the\constant{AF_INET} address family, where \var{host} is a stringrepresenting either a hostname in Internet domain notation like\code{'daring.cwi.nl'} or an IPv4 address like \code{'100.50.200.5'},and \var{port} is an integral port number.For \constant{AF_INET6} address family, a four-tuple\code{(\var{host}, \var{port}, \var{flowinfo}, \var{scopeid})} isused, where \var{flowinfo} and \var{scopeid} represents\code{sin6_flowinfo} and \code{sin6_scope_id} member in\constant{struct sockaddr_in6} in C.For \module{socket} module methods, \var{flowinfo} and \var{scopeid}can be omitted just for backward compatibility. Note, however,omission of \var{scopeid} can cause problems in manipulating scopedIPv6 addresses. Other address families are currently not supported.The address format required by a particular socket object isautomatically selected based on the address family specified when thesocket object was created. For IPv4 addresses, two special forms are accepted instead of a hostaddress: the empty string represents \constant{INADDR_ANY}, and the string\code{'<broadcast>'} represents \constant{INADDR_BROADCAST}.The behavior is not available for IPv6 for backward compatibility,therefore, you may want to avoid these if you intend to support IPv6 withyour Python programs. If you use a hostname in the \var{host} portion of IPv4/v6 socketaddress, the program may show a nondeterministic behavior, as Pythonuses the first address returned from the DNS resolution.  The socketaddress will be resolved differently into an actual IPv4/v6 address,depending on the results from DNS resolution and/or the hostconfiguration.  For deterministic behavior use a numeric address in\var{host} portion. \versionadded[AF_NETLINK sockets are represented as pairs \code{\var{pid}, \var{groups}}]{2.5} All errors raise exceptions.  The normal exceptions for invalidargument types and out-of-memory conditions can be raised; errorsrelated to socket or address semantics raise the error\exception{socket.error}. Non-blocking mode is supported through\method{setblocking()}.  A generalization of this based on timeoutsis supported through \method{settimeout()}. The module \module{socket} exports the following constants and functions:  \begin{excdesc}{error}This exception is raised for socket-related errors.The accompanying value is either a string telling what went wrong or apair \code{(\var{errno}, \var{string})}representing an error returned by a systemcall, similar to the value accompanying \exception{os.error}.See the module \refmodule{errno}\refbimodindex{errno}, which containsnames for the error codes defined by the underlying operating system.\end{excdesc} \begin{excdesc}{herror}This exception is raised for address-related errors, i.e. forfunctions that use \var{h_errno} in the C API, including\function{gethostbyname_ex()} and \function{gethostbyaddr()}. The accompanying value is a pair \code{(\var{h_errno}, \var{string})}representing an error returned by a library call. \var{string}represents the description of \var{h_errno}, as returned bythe \cfunction{hstrerror()} C function.\end{excdesc} \begin{excdesc}{gaierror}This exception is raised for address-related errors, for\function{getaddrinfo()} and \function{getnameinfo()}.The accompanying value is a pair \code{(\var{error}, \var{string})}representing an error returned by a library call.\var{string} represents the description of \var{error}, as returnedby the \cfunction{gai_strerror()} C function.The \var{error} value will match one of the \constant{EAI_*} constantsdefined in this module.\end{excdesc} \begin{excdesc}{timeout}This exception is raised when a timeout occurs on a socket which hashad timeouts enabled via a prior call to \method{settimeout()}.  Theaccompanying value is a string whose value is currently always ``timedout''.\versionadded{2.3}\end{excdesc} \begin{datadesc}{AF_UNIX}\dataline{AF_INET}\dataline{AF_INET6}These constants represent the address (and protocol) families,used for the first argument to \function{socket()}.  If the\constant{AF_UNIX} constant is not defined then this protocol isunsupported.\end{datadesc} \begin{datadesc}{SOCK_STREAM}\dataline{SOCK_DGRAM}\dataline{SOCK_RAW}\dataline{SOCK_RDM}\dataline{SOCK_SEQPACKET}These constants represent the socket types,used for the second argument to \function{socket()}.(Only \constant{SOCK_STREAM} and\constant{SOCK_DGRAM} appear to be generally useful.)\end{datadesc} \begin{datadesc}{SO_*}\dataline{SOMAXCONN}\dataline{MSG_*}\dataline{SOL_*}\dataline{IPPROTO_*}\dataline{IPPORT_*}\dataline{INADDR_*}\dataline{IP_*}\dataline{IPV6_*}\dataline{EAI_*}\dataline{AI_*}\dataline{NI_*}\dataline{TCP_*}Many constants of these forms, documented in the \UNIX{} documentation onsockets and/or the IP protocol, are also defined in the socket module.They are generally used in arguments to the \method{setsockopt()} and\method{getsockopt()} methods of socket objects.  In most cases, onlythose symbols that are defined in the \UNIX{} header files are defined;for a few symbols, default values are provided.\end{datadesc} \begin{datadesc}{has_ipv6}This constant contains a boolean value which indicates if IPv6 issupported on this platform.\versionadded{2.3}\end{datadesc} \begin{funcdesc}{getaddrinfo}{host, port\optional{, family\optional{,                              socktype\optional{, proto\optional{,                              flags}}}}}Resolves the \var{host}/\var{port} argument, into a sequence of5-tuples that contain all the necessary argument for the socketsmanipulation. \var{host} is a domain name, a string representation ofIPv4/v6 address or \code{None}.\var{port} is a string service name (like \code{'http'}), a numericport number or \code{None}. The rest of the arguments are optional and must be numeric ifspecified.  For \var{host} and \var{port}, by passing either an emptystring or \code{None}, you can pass \code{NULL} to the C API.  The\function{getaddrinfo()} function returns a list of 5-tuples withthe following structure: \code{(\var{family}, \var{socktype}, \var{proto}, \var{canonname},      \var{sockaddr})} \var{family}, \var{socktype}, \var{proto} are all integer and are meant tobe passed to the \function{socket()} function.\var{canonname} is a string representing the canonical name of the \var{host}.It can be a numeric IPv4/v6 address when \constant{AI_CANONNAME} is specifiedfor a numeric \var{host}.\var{sockaddr} is a tuple describing a socket address, as described above.See the source for the \refmodule{httplib} and other library modulesfor a typical usage of the function.\versionadded{2.2}\end{funcdesc} \begin{funcdesc}{getfqdn}{\optional{name}}Return a fully qualified domain name for \var{name}.If \var{name} is omitted or empty, it is interpreted as the localhost.  To find the fully qualified name, the hostname returned by\function{gethostbyaddr()} is checked, then aliases for the host, ifavailable.  The first name which includes a period is selected.  Incase no fully qualified domain name is available, the hostname asreturned by \function{gethostname()} is returned.\versionadded{2.0}\end{funcdesc} \begin{funcdesc}{gethostbyname}{hostname}Translate a host name to IPv4 address format.  The IPv4 address isreturned as a string, such as  \code{'100.50.200.5'}.  If the host nameis an IPv4 address itself it is returned unchanged.  See\function{gethostbyname_ex()} for a more complete interface.\function{gethostbyname()} does not support IPv6 name resolution, and\function{getaddrinfo()} should be used instead for IPv4/v6 dual stack support.\end{funcdesc} \begin{funcdesc}{gethostbyname_ex}{hostname}Translate a host name to IPv4 address format, extended interface.Return a triple \code{(\var{hostname}, \var{aliaslist},\var{ipaddrlist})} where\var{hostname} is the primary host name responding to the given\var{ip_address}, \var{aliaslist} is a (possibly empty) list ofalternative host names for the same address, and \var{ipaddrlist} isa list of IPv4 addresses for the same interface on the samehost (often but not always a single address).\function{gethostbyname_ex()} does not support IPv6 name resolution, and\function{getaddrinfo()} should be used instead for IPv4/v6 dual stack support.\end{funcdesc} \begin{funcdesc}{gethostname}{}Return a string containing the hostname of the machine where the Python interpreter is currently executing.If you want to know the current machine's IP address, you may want to use\code{gethostbyname(gethostname())}.This operation assumes that there is a valid address-to-host mapping forthe host, and the assumption does not always hold.Note: \function{gethostname()} doesn't always return the fully qualifieddomain name; use \code{getfqdn()}(see above).\end{funcdesc} \begin{funcdesc}{gethostbyaddr}{ip_address}Return a triple \code{(\var{hostname}, \var{aliaslist},\var{ipaddrlist})} where \var{hostname} is the primary host nameresponding to the given \var{ip_address}, \var{aliaslist} is a(possibly empty) list of alternative host names for the same address,and \var{ipaddrlist} is a list of IPv4/v6 addresses for the same interfaceon the same host (most likely containing only a single address).To find the fully qualified domain name, use the function\function{getfqdn()}.\function{gethostbyaddr} supports both IPv4 and IPv6.\end{funcdesc} \begin{funcdesc}{getnameinfo}{sockaddr, flags}Translate a socket address \var{sockaddr} into a 2-tuple\code{(\var{host}, \var{port})}.Depending on the settings of \var{flags}, the result can contain afully-qualified domain name or numeric address representation in\var{host}.  Similarly, \var{port} can contain a string port name or anumeric port number.\versionadded{2.2}\end{funcdesc} \begin{funcdesc}{getprotobyname}{protocolname}Translate an Internet protocol name (for example, \code{'icmp'}) to a constantsuitable for passing as the (optional) third argument to the\function{socket()} function.  This is usually only needed for socketsopened in ``raw'' mode (\constant{SOCK_RAW}); for the normal socketmodes, the correct protocol is chosen automatically if the protocol isomitted or zero.\end{funcdesc} \begin{funcdesc}{getservbyname}{servicename\optional{, protocolname}}Translate an Internet service name and protocol name to a port numberfor that service.  The optional protocol name, if given, should be\code{'tcp'} or \code{'udp'}, otherwise any protocol will match.\end{funcdesc} \begin{funcdesc}{getservbyport}{port\optional{, protocolname}}Translate an Internet port number and protocol name to a service namefor that service.  The optional protocol name, if given, should be\code{'tcp'} or \code{'udp'}, otherwise any protocol will match.\end{funcdesc} \begin{funcdesc}{socket}{\optional{family\optional{,                         type\optional{, proto}}}}Create a new socket using the given address family, socket type andprotocol number.  The address family should be \constant{AF_INET} (thedefault), \constant{AF_INET6} or \constant{AF_UNIX}.  The socket typeshould be \constant{SOCK_STREAM} (the default), \constant{SOCK_DGRAM}or perhaps one of the other \samp{SOCK_} constants.  The protocolnumber is usually zero and may be omitted in that case.\end{funcdesc} \begin{funcdesc}{ssl}{sock\optional{, keyfile, certfile}}Initiate a SSL connection over the socket \var{sock}. \var{keyfile} isthe name of a PEM formatted file that contains your privatekey. \var{certfile} is a PEM formatted certificate chain file. Onsuccess, a new \class{SSLObject} is returned. \warning{This does not do any certificate verification!}\end{funcdesc} \begin{funcdesc}{socketpair}{\optional{family\optional{, type\optional{, proto}}}}Build a pair of connected socket objects using the given addressfamily, socket type, and protocol number.  Address family, socket type,and protocol number are as for the \function{socket()} function above.The default family is \constant{AF_UNIX} if defined on the platform;otherwise, the default is \constant{AF_INET}.Availability: \UNIX.  \versionadded{2.4}\end{funcdesc} \begin{funcdesc}{fromfd}{fd, family, type\optional{, proto}}Duplicate the file descriptor \var{fd} (an integer as returned by a fileobject's \method{fileno()} method) and build a socket object from theresult.  Address family, socket type and protocol number are as for the\function{socket()} function above.The file descriptor should refer to a socket, but this is notchecked --- subsequent operations on the object may fail if the filedescriptor is invalid.  This function is rarely needed, but can beused to get or set socket options on a socket passed to a program asstandard input or output (such as a server started by the \UNIX{} inetdaemon).  The socket is assumed to be in blocking mode.Availability: \UNIX.\end{funcdesc} \begin{funcdesc}{ntohl}{x}Convert 32-bit integers from network to host byte order.  On machineswhere the host byte order is the same as network byte order, this is ano-op; otherwise, it performs a 4-byte swap operation.\end{funcdesc} \begin{funcdesc}{ntohs}{x}Convert 16-bit integers from network to host byte order.  On machineswhere the host byte order is the same as network byte order, this is ano-op; otherwise, it performs a 2-byte swap operation.\end{funcdesc} \begin{funcdesc}{htonl}{x}Convert 32-bit integers from host to network byte order.  On machineswhere the host byte order is the same as network byte order, this is ano-op; otherwise, it performs a 4-byte swap operation.\end{funcdesc} \begin{funcdesc}{htons}{x}Convert 16-bit integers from host to network byte order.  On machineswhere the host byte order is the same as network byte order, this is ano-op; otherwise, it performs a 2-byte swap operation.\end{funcdesc} \begin{funcdesc}{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 string fourcharacters in length.  This is useful when conversing with a programthat uses the standard C library and needs objects of type\ctype{struct in_addr}, which is the C type for the 32-bit packedbinary this function returns. If the IPv4 address string passed to this function is invalid,\exception{socket.error} will be raised. Note that exactly what isvalid depends on the underlying C implementation of\cfunction{inet_aton()}. \function{inet_aton()} does not support IPv6, and\function{getnameinfo()} should be used instead for IPv4/v6 dual stacksupport.\end{funcdesc} \begin{funcdesc}{inet_ntoa}{packed_ip}Convert a 32-bit packed IPv4 address (a string four characters inlength) to its standard dotted-quad string representation (forexample, '123.45.67.89').  This is useful when conversing with aprogram that uses the standard C library and needs objects of type\ctype{struct in_addr}, which is the C type for the 32-bit packedbinary data this function takes as an argument. If the string passed to this function is not exactly 4 bytes inlength, \exception{socket.error} will be raised.\function{inet_ntoa()} does not support IPv6, and\function{getnameinfo()} should be used instead for IPv4/v6 dual stacksupport.\end{funcdesc} \begin{funcdesc}{inet_pton}{address_family, ip_string}Convert an IP address from its family-specific string format to a packed,binary format.\function{inet_pton()} is useful when a library or network protocol calls foran object of type \ctype{struct in_addr} (similar to \function{inet_aton()})or \ctype{struct in6_addr}. Supported values for \var{address_family} are currently\constant{AF_INET} and \constant{AF_INET6}.If the IP address string \var{ip_string} is invalid,\exception{socket.error} will be raised. Note that exactly what is validdepends on both the value of \var{address_family} and the underlyingimplementation of \cfunction{inet_pton()}. Availability: \UNIX{} (maybe not all platforms).\versionadded{2.3}\end{funcdesc} \begin{funcdesc}{inet_ntop}{address_family, packed_ip}Convert a packed IP address (a string of some number of characters) toits standard, family-specific string representation (for example,\code{'7.10.0.5'} or \code{'5aef:2b::8'})\function{inet_ntop()} is useful when a library or network protocol returnsan object of type \ctype{struct in_addr} (similar to \function{inet_ntoa()})or \ctype{struct in6_addr}. Supported values for \var{address_family} are currently\constant{AF_INET} and \constant{AF_INET6}.If the string \var{packed_ip} is not the correct length for thespecified address family, \exception{ValueError} will be raised.  A\exception{socket.error} is raised for errors from the call to\function{inet_ntop()}. Availability: \UNIX{} (maybe not all platforms).\versionadded{2.3}\end{funcdesc} \begin{funcdesc}{getdefaulttimeout}{}Return the default timeout in floating seconds for new socket objects.A value of \code{None} indicates that new socket objects have no timeout.When the socket module is first imported, the default is \code{None}.\versionadded{2.3}\end{funcdesc} \begin{funcdesc}{setdefaulttimeout}{timeout}Set the default timeout in floating seconds for new socket objects.A value of \code{None} indicates that new socket objects have no timeout.When the socket module is first imported, the default is \code{None}.\versionadded{2.3}\end{funcdesc} \begin{datadesc}{SocketType}This is a Python type object that represents the socket object type.It is the same as \code{type(socket(...))}.\end{datadesc}  \begin{seealso}  \seemodule{SocketServer}{Classes that simplify writing network servers.}\end{seealso}  \subsection{Socket Objects \label{socket-objects}} Socket objects have the following methods.  Except for\method{makefile()} these correspond to \UNIX{} system callsapplicable to sockets. \begin{methoddesc}[socket]{accept}{}Accept a connection.The socket must be bound to an address and listening for connections.The return value is a pair \code{(\var{conn}, \var{address})}where \var{conn} is a \emph{new} socket object usable to send andreceive data on the connection, and \var{address} is the address boundto the socket on the other end of the connection.\end{methoddesc} \begin{methoddesc}[socket]{bind}{address}Bind the socket to \var{address}.  The socket must not already be bound.(The format of \var{address} depends on the address family --- seeabove.)  \note{This method has historically accepted a pairof parameters for \constant{AF_INET} addresses instead of only atuple.  This was never intentional and is no longer available inPython 2.0 and later.}\end{methoddesc} \begin{methoddesc}[socket]{close}{}Close the socket.  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.\end{methoddesc} \begin{methoddesc}[socket]{connect}{address}Connect to a remote socket at \var{address}.(The format of \var{address} depends on the address family --- seeabove.)  \note{This method has historically accepted a pairof parameters for \constant{AF_INET} addresses instead of only atuple.  This was never intentional and is no longer available inPython 2.0 and later.}\end{methoddesc} \begin{methoddesc}[socket]{connect_ex}{address}Like \code{connect(\var{address})}, but return an error indicatorinstead of raising an exception for errors returned by the C-level\cfunction{connect()} call (other problems, such as ``host not found,''can still raise exceptions).  The error indicator is \code{0} if theoperation succeeded, otherwise the value of the \cdata{errno}variable.  This is useful to support, for example, asynchronous connects.\note{This method has historically accepted a pair ofparameters for \constant{AF_INET} addresses instead of only a tuple.This was never intentional and is no longer available in Python

Lines 1–500 of 910.