17.2. socket — Low-level networking interface¶
This module provides access to the BSD socket interface. It is available on all modern Unix systems, Windows, Mac OS X, BeOS, OS/2, and probably additional platforms.
Note
Some behavior may be platform dependent, since calls are made to the operating system socket APIs.
For an introduction to socket programming (in C), see the following papers: An Introductory 4.3BSD Interprocess Communication Tutorial, by Stuart Sechrest and An Advanced 4.3BSD Interprocess Communication Tutorial, by Samuel J. Leffler et al, both in the UNIX Programmer’s Manual, Supplementary Documents 1 (sections PS1:7 and PS1:8). The platform-specific reference material for the various socket-related system calls are also a valuable source of information on the details of socket semantics. For Unix, refer to the manual pages; for Windows, see the WinSock (or Winsock 2) specification. For IPv6-ready APIs, readers may want to refer to RFC 3493 titled 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’s object-oriented style: the
socket() function returns a socket object whose methods implement
the various socket system calls. Parameter types are somewhat higher-level than
in the C interface: as with read() and write() operations on Python
files, buffer allocation on receive operations is automatic, and buffer length
is implicit on send operations.
Socket addresses are represented as follows: A single string is used for the
AF_UNIX address family. A pair (host, port) is used for the
AF_INET address family, where host is a string representing either a
hostname in Internet domain notation like 'daring.cwi.nl' or an IPv4 address
like '100.50.200.5', and port is an integer. For
AF_INET6 address family, a four-tuple (host, port, flowinfo,
scopeid) is used, where flowinfo and scopeid represents sin6_flowinfo
and sin6_scope_id member in struct sockaddr_in6 in C. For
socket module methods, flowinfo and scopeid can be omitted just for
backward compatibility. Note, however, omission of scopeid can cause problems
in manipulating scoped IPv6 addresses. Other address families are currently not
supported. The address format required by a particular socket object is
automatically selected based on the address family specified when the socket
object was created.
For IPv4 addresses, two special forms are accepted instead of a host address:
the empty string represents INADDR_ANY, and the string
'<broadcast>' represents 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 with your Python programs.
If you use a hostname in the host portion of IPv4/v6 socket address, the program may show a nondeterministic behavior, as Python uses the first address returned from the DNS resolution. The socket address will be resolved differently into an actual IPv4/v6 address, depending on the results from DNS resolution and/or the host configuration. For deterministic behavior use a numeric address in host portion.
New in version 2.5: AF_NETLINK sockets are represented as pairs pid, groups.
New in version 2.6: Linux-only support for TIPC is also available using the AF_TIPC
address family. TIPC is an open, non-IP based networked protocol designed
for use in clustered computer environments. Addresses are represented by a
tuple, and the fields depend on the address type. The general tuple form is
(addr_type, v1, v2, v3 [, scope]), where:
addr_type is one of
TIPC_ADDR_NAMESEQ,TIPC_ADDR_NAME, orTIPC_ADDR_ID.scope is one of
TIPC_ZONE_SCOPE,TIPC_CLUSTER_SCOPE, andTIPC_NODE_SCOPE.If addr_type is
TIPC_ADDR_NAME, then v1 is the server type, v2 is the port identifier, and v3 should be 0.If addr_type is
TIPC_ADDR_NAMESEQ, then v1 is the server type, v2 is the lower port number, and v3 is the upper port number.If addr_type is
TIPC_ADDR_ID, then v1 is the node, v2 is the reference, and v3 should be set to 0.
All errors raise exceptions. The normal exceptions for invalid argument types
and out-of-memory conditions can be raised; errors related to socket or address
semantics raise the error socket.error.
Non-blocking mode is supported through setblocking(). A
generalization of this based on timeouts is supported through
settimeout().
The module socket exports the following constants and functions:
-
exception
socket.error¶ This exception is raised for socket-related errors. The accompanying value is either a string telling what went wrong or a pair
(errno, string)representing an error returned by a system call, similar to the value accompanyingos.error. See the moduleerrno, which contains names for the error codes defined by the underlying operating system.Changed in version 2.6:
socket.erroris now a child class ofIOError.
-
exception
socket.herror¶ This exception is raised for address-related errors, i.e. for functions that use h_errno in the C API, including
gethostbyname_ex()andgethostbyaddr().The accompanying value is a pair
(h_errno, string)representing an error returned by a library call. string represents the description of h_errno, as returned by thehstrerror()C function.
-
exception
socket.gaierror¶ This exception is raised for address-related errors, for
getaddrinfo()andgetnameinfo(). The accompanying value is a pair(error, string)representing an error returned by a library call. string represents the description of error, as returned by thegai_strerror()C function. The error value will match one of theEAI_*constants defined in this module.
-
exception
socket.timeout¶ This exception is raised when a timeout occurs on a socket which has had timeouts enabled via a prior call to
settimeout(). The accompanying value is a string whose value is currently always “timed out”.New in version 2.3.
-
socket.AF_UNIX¶ -
socket.AF_INET¶ -
socket.AF_INET6¶ These constants represent the address (and protocol) families, used for the first argument to
socket(). If theAF_UNIXconstant is not defined then this protocol is unsupported.
-
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(). (OnlySOCK_STREAMandSOCK_DGRAMappear to be generally useful.)
-
SO_* -
socket.SOMAXCONN¶ -
MSG_* -
SOL_* -
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()andgetsockopt()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.
-
SIO_* -
RCVALL_* Constants for Windows’ WSAIoctl(). The constants are used as arguments to the
ioctl()method of socket objects.New in version 2.6.
-
TIPC_* TIPC related constants, matching the ones exported by the C socket API. See the TIPC documentation for more information.
New in version 2.6.
-
socket.has_ipv6¶ This constant contains a boolean value which indicates if IPv6 is supported on this platform.
New in version 2.3.
-
socket.create_connection(address[, timeout[, source_address]])¶ 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 thansocket.connect(): if host is a non-numeric hostname, it will try to resolve it for bothAF_INETandAF_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.Passing the optional timeout parameter will set the timeout on the socket instance before attempting to connect. If no timeout is supplied, the global default timeout setting returned by
getdefaulttimeout()is used.If supplied, source_address must be a 2-tuple
(host, port)for the socket to bind to as its source address before connecting. If host or port are ‘’ or 0 respectively the OS default behavior will be used.New in version 2.6.
Changed in version 2.7: source_address was added.
-
socket.getaddrinfo(host, port[, family[, socktype[, proto[, flags]]]])¶ Translate the host/port argument into a sequence of 5-tuples that contain all the necessary arguments for creating a socket connected to that service. host is a domain name, a string representation of an IPv4/v6 address or
None. port is a string service name such as'http', a numeric port number orNone. By passingNoneas the value of host and port, you can passNULLto the underlying C API.The family, socktype and proto arguments can be optionally specified in order to narrow the list of addresses returned. By default, their value is
0, meaning that the full range of results is selected. The flags argument can be one or several of theAI_*constants, and will influence how results are computed and returned. Its default value is0. For example,AI_NUMERICHOSTwill disable domain name resolution and will raise an error if host is a domain name.The function returns a list of 5-tuples with the following structure:
(family, socktype, proto, canonname, sockaddr)In these tuples, family, socktype, proto are all integers and are meant to be passed to the
socket()function. canonname will be a string representing the canonical name of the host ifAI_CANONNAMEis part of the flags argument; else canonname will be empty. sockaddr is a tuple describing a socket address, whose format depends on the returned family (a(address, port)2-tuple forAF_INET, a(address, port, flow info, scope id)4-tuple forAF_INET6), and is meant to be passed to thesocket.connect()method.The following example fetches address information for a hypothetical TCP connection to
example.orgon port 80 (results may differ on your system if IPv6 isn’t enabled):>>> socket.getaddrinfo("example.org", 80, 0, 0, socket.IPPROTO_TCP) [(10, 1, 6, '', ('2606:2800:220:1:248:1893:25c8:1946', 80, 0, 0)), (2, 1, 6, '', ('93.184.216.34', 80))]
New in version 2.2.
-
socket.getfqdn([name])¶ Return a fully qualified domain name for name. If name is omitted or empty, it is interpreted as the local host. To find the fully qualified name, the hostname returned by
gethostbyaddr()is checked, followed by aliases for the host, if available. The first name which includes a period is selected. In case no fully qualified domain name is available, the hostname as returned bygethostname()is returned.New in version 2.0.
-
socket.gethostbyname
