Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame^] | 1 | |
| 2 | :mod:`socket` --- Low-level networking interface |
| 3 | ================================================ |
| 4 | |
| 5 | .. module:: socket |
| 6 | :synopsis: Low-level networking interface. |
| 7 | |
| 8 | |
| 9 | This module provides access to the BSD *socket* interface. It is available on |
| 10 | all modern Unix systems, Windows, MacOS, BeOS, OS/2, and probably additional |
| 11 | platforms. |
| 12 | |
| 13 | .. note:: |
| 14 | |
| 15 | Some behavior may be platform dependent, since calls are made to the operating |
| 16 | system socket APIs. |
| 17 | |
| 18 | For an introduction to socket programming (in C), see the following papers: An |
| 19 | Introductory 4.3BSD Interprocess Communication Tutorial, by Stuart Sechrest and |
| 20 | An Advanced 4.3BSD Interprocess Communication Tutorial, by Samuel J. Leffler et |
| 21 | al, both in the UNIX Programmer's Manual, Supplementary Documents 1 (sections |
| 22 | PS1:7 and PS1:8). The platform-specific reference material for the various |
| 23 | socket-related system calls are also a valuable source of information on the |
| 24 | details of socket semantics. For Unix, refer to the manual pages; for Windows, |
| 25 | see the WinSock (or Winsock 2) specification. For IPv6-ready APIs, readers may |
| 26 | want to refer to :rfc:`2553` titled Basic Socket Interface Extensions for IPv6. |
| 27 | |
| 28 | .. index:: object: socket |
| 29 | |
| 30 | The Python interface is a straightforward transliteration of the Unix system |
| 31 | call and library interface for sockets to Python's object-oriented style: the |
| 32 | :func:`socket` function returns a :dfn:`socket object` whose methods implement |
| 33 | the various socket system calls. Parameter types are somewhat higher-level than |
| 34 | in the C interface: as with :meth:`read` and :meth:`write` operations on Python |
| 35 | files, buffer allocation on receive operations is automatic, and buffer length |
| 36 | is implicit on send operations. |
| 37 | |
| 38 | Socket addresses are represented as follows: A single string is used for the |
| 39 | :const:`AF_UNIX` address family. A pair ``(host, port)`` is used for the |
| 40 | :const:`AF_INET` address family, where *host* is a string representing either a |
| 41 | hostname in Internet domain notation like ``'daring.cwi.nl'`` or an IPv4 address |
| 42 | like ``'100.50.200.5'``, and *port* is an integral port number. For |
| 43 | :const:`AF_INET6` address family, a four-tuple ``(host, port, flowinfo, |
| 44 | scopeid)`` is used, where *flowinfo* and *scopeid* represents ``sin6_flowinfo`` |
| 45 | and ``sin6_scope_id`` member in :const:`struct sockaddr_in6` in C. For |
| 46 | :mod:`socket` module methods, *flowinfo* and *scopeid* can be omitted just for |
| 47 | backward compatibility. Note, however, omission of *scopeid* can cause problems |
| 48 | in manipulating scoped IPv6 addresses. Other address families are currently not |
| 49 | supported. The address format required by a particular socket object is |
| 50 | automatically selected based on the address family specified when the socket |
| 51 | object was created. |
| 52 | |
| 53 | For IPv4 addresses, two special forms are accepted instead of a host address: |
| 54 | the empty string represents :const:`INADDR_ANY`, and the string |
| 55 | ``'<broadcast>'`` represents :const:`INADDR_BROADCAST`. The behavior is not |
| 56 | available for IPv6 for backward compatibility, therefore, you may want to avoid |
| 57 | these if you intend to support IPv6 with your Python programs. |
| 58 | |
| 59 | If you use a hostname in the *host* portion of IPv4/v6 socket address, the |
| 60 | program may show a nondeterministic behavior, as Python uses the first address |
| 61 | returned from the DNS resolution. The socket address will be resolved |
| 62 | differently into an actual IPv4/v6 address, depending on the results from DNS |
| 63 | resolution and/or the host configuration. For deterministic behavior use a |
| 64 | numeric address in *host* portion. |
| 65 | |
| 66 | .. versionadded:: 2.5 |
| 67 | AF_NETLINK sockets are represented as pairs ``pid, groups``. |
| 68 | |
| 69 | All errors raise exceptions. The normal exceptions for invalid argument types |
| 70 | and out-of-memory conditions can be raised; errors related to socket or address |
| 71 | semantics raise the error :exc:`socket.error`. |
| 72 | |
| 73 | Non-blocking mode is supported through :meth:`setblocking`. A generalization of |
| 74 | this based on timeouts is supported through :meth:`settimeout`. |
| 75 | |
| 76 | The module :mod:`socket` exports the following constants and functions: |
| 77 | |
| 78 | |
| 79 | .. exception:: error |
| 80 | |
| 81 | .. index:: module: errno |
| 82 | |
| 83 | This exception is raised for socket-related errors. The accompanying value is |
| 84 | either a string telling what went wrong or a pair ``(errno, string)`` |
| 85 | representing an error returned by a system call, similar to the value |
| 86 | accompanying :exc:`os.error`. See the module :mod:`errno`, which contains names |
| 87 | for the error codes defined by the underlying operating system. |
| 88 | |
| 89 | |
| 90 | .. exception:: herror |
| 91 | |
| 92 | This exception is raised for address-related errors, i.e. for functions that use |
| 93 | *h_errno* in the C API, including :func:`gethostbyname_ex` and |
| 94 | :func:`gethostbyaddr`. |
| 95 | |
| 96 | The accompanying value is a pair ``(h_errno, string)`` representing an error |
| 97 | returned by a library call. *string* represents the description of *h_errno*, as |
| 98 | returned by the :cfunc:`hstrerror` C function. |
| 99 | |
| 100 | |
| 101 | .. exception:: gaierror |
| 102 | |
| 103 | This exception is raised for address-related errors, for :func:`getaddrinfo` and |
| 104 | :func:`getnameinfo`. The accompanying value is a pair ``(error, string)`` |
| 105 | representing an error returned by a library call. *string* represents the |
| 106 | description of *error*, as returned by the :cfunc:`gai_strerror` C function. The |
| 107 | *error* value will match one of the :const:`EAI_\*` constants defined in this |
| 108 | module. |
| 109 | |
| 110 | |
| 111 | .. exception:: timeout |
| 112 | |
| 113 | This exception is raised when a timeout occurs on a socket which has had |
| 114 | timeouts enabled via a prior call to :meth:`settimeout`. The accompanying value |
| 115 | is a string whose value is currently always "timed out". |
| 116 | |
| 117 | .. versionadded:: 2.3 |
| 118 | |
| 119 | |
| 120 | .. data:: AF_UNIX |
| 121 | AF_INET |
| 122 | AF_INET6 |
| 123 | |
| 124 | These constants represent the address (and protocol) families, used for the |
| 125 | first argument to :func:`socket`. If the :const:`AF_UNIX` constant is not |
| 126 | defined then this protocol is unsupported. |
| 127 | |
| 128 | |
| 129 | .. data:: SOCK_STREAM |
| 130 | SOCK_DGRAM |
| 131 | SOCK_RAW |
| 132 | SOCK_RDM |
| 133 | SOCK_SEQPACKET |
| 134 | |
| 135 | These constants represent the socket types, used for the second argument to |
| 136 | :func:`socket`. (Only :const:`SOCK_STREAM` and :const:`SOCK_DGRAM` appear to be |
| 137 | generally useful.) |
| 138 | |
| 139 | |
| 140 | .. data:: SO_* |
| 141 | SOMAXCONN |
| 142 | MSG_* |
| 143 | SOL_* |
| 144 | IPPROTO_* |
| 145 | IPPORT_* |
| 146 | INADDR_* |
| 147 | IP_* |
| 148 | IPV6_* |
| 149 | EAI_* |
| 150 | AI_* |
| 151 | NI_* |
| 152 | TCP_* |
| 153 | |
| 154 | Many constants of these forms, documented in the Unix documentation on sockets |
| 155 | and/or the IP protocol, are also defined in the socket module. They are |
| 156 | generally used in arguments to the :meth:`setsockopt` and :meth:`getsockopt` |
| 157 | methods of socket objects. In most cases, only those symbols that are defined |
| 158 | in the Unix header files are defined; for a few symbols, default values are |
| 159 | provided. |
| 160 | |
| 161 | |
| 162 | .. data:: has_ipv6 |
| 163 | |
| 164 | This constant contains a boolean value which indicates if IPv6 is supported on |
| 165 | this platform. |
| 166 | |
| 167 | .. versionadded:: 2.3 |
| 168 | |
| 169 | |
| 170 | .. function:: create_connection(address[, timeout]) |
| 171 | |
| 172 | Connects to the *address* received (as usual, a ``(host, port)`` pair), with an |
| 173 | optional timeout for the connection. Specially useful for higher-level |
| 174 | protocols, it is not normally used directly from application-level code. |
| 175 | Passing the optional *timeout* parameter will set the timeout on the socket |
| 176 | instance (if it is not given or ``None``, the global default timeout setting is |
| 177 | used). |
| 178 | |
| 179 | .. versionadded:: 2.6 |
| 180 | |
| 181 | |
| 182 | .. function:: getaddrinfo(host, port[, family[, socktype[, proto[, flags]]]]) |
| 183 | |
| 184 | Resolves the *host*/*port* argument, into a sequence of 5-tuples that contain |
| 185 | all the necessary argument for the sockets manipulation. *host* is a domain |
| 186 | name, a string representation of IPv4/v6 address or ``None``. *port* is a string |
| 187 | service name (like ``'http'``), a numeric port number or ``None``. |
| 188 | |
| 189 | The rest of the arguments are optional and must be numeric if specified. For |
| 190 | *host* and *port*, by passing either an empty string or ``None``, you can pass |
| 191 | ``NULL`` to the C API. The :func:`getaddrinfo` function returns a list of |
| 192 | 5-tuples with the following structure: |
| 193 | |
| 194 | ``(family, socktype, proto, canonname, sockaddr)`` |
| 195 | |
| 196 | *family*, *socktype*, *proto* are all integer and are meant to be passed to the |
| 197 | :func:`socket` function. *canonname* is a string representing the canonical name |
| 198 | of the *host*. It can be a numeric IPv4/v6 address when :const:`AI_CANONNAME` is |
| 199 | specified for a numeric *host*. *sockaddr* is a tuple describing a socket |
| 200 | address, as described above. See the source for the :mod:`httplib` and other |
| 201 | library modules for a typical usage of the function. |
| 202 | |
| 203 | .. versionadded:: 2.2 |
| 204 | |
| 205 | |
| 206 | .. function:: getfqdn([name]) |
| 207 | |
| 208 | Return a fully qualified domain name for *name*. If *name* is omitted or empty, |
| 209 | it is interpreted as the local host. To find the fully qualified name, the |
| 210 | hostname returned by :func:`gethostbyaddr` is checked, then aliases for the |
| 211 | host, if available. The first name which includes a period is selected. In |
| 212 | case no fully qualified domain name is available, the hostname as returned by |
| 213 | :func:`gethostname` is returned. |
| 214 | |
| 215 | .. versionadded:: 2.0 |
| 216 | |
| 217 | |
| 218 | .. function:: gethostbyname(hostname) |
| 219 | |
| 220 | Translate a host name to IPv4 address format. The IPv4 address is returned as a |
| 221 | string, such as ``'100.50.200.5'``. If the host name is an IPv4 address itself |
| 222 | it is returned unchanged. See :func:`gethostbyname_ex` for a more complete |
| 223 | interface. :func:`gethostbyname` does not support IPv6 name resolution, and |
| 224 | :func:`getaddrinfo` should be used instead for IPv4/v6 dual stack support. |
| 225 | |
| 226 | |
| 227 | .. function:: gethostbyname_ex(hostname) |
| 228 | |
| 229 | Translate a host name to IPv4 address format, extended interface. Return a |
| 230 | triple ``(hostname, aliaslist, ipaddrlist)`` where *hostname* is the primary |
| 231 | host name responding to the given *ip_address*, *aliaslist* is a (possibly |
| 232 | empty) list of alternative host names for the same address, and *ipaddrlist* is |
| 233 | a list of IPv4 addresses for the same interface on the same host (often but not |
| 234 | always a single address). :func:`gethostbyname_ex` does not support IPv6 name |
| 235 | resolution, and :func:`getaddrinfo` should be used instead for IPv4/v6 dual |
| 236 | stack support. |
| 237 | |
| 238 | |
| 239 | .. function:: gethostname() |
| 240 | |
| 241 | Return a string containing the hostname of the machine where the Python |
| 242 | interpreter is currently executing. If you want to know the current machine's IP |
| 243 | address, you may want to use ``gethostbyname(gethostname())``. This operation |
| 244 | assumes that there is a valid address-to-host mapping for the host, and the |
| 245 | assumption does not always hold. Note: :func:`gethostname` doesn't always return |
| 246 | the fully qualified domain name; use ``getfqdn()`` (see above). |
| 247 | |
| 248 | |
| 249 | .. function:: gethostbyaddr(ip_address) |
| 250 | |
| 251 | Return a triple ``(hostname, aliaslist, ipaddrlist)`` where *hostname* is the |
| 252 | primary host name responding to the given *ip_address*, *aliaslist* is a |
| 253 | (possibly empty) list of alternative host names for the same address, and |
| 254 | *ipaddrlist* is a list of IPv4/v6 addresses for the same interface on the same |
| 255 | host (most likely containing only a single address). To find the fully qualified |
| 256 | domain name, use the function :func:`getfqdn`. :func:`gethostbyaddr` supports |
| 257 | both IPv4 and IPv6. |
| 258 | |
| 259 | |
| 260 | .. function:: getnameinfo(sockaddr, flags) |
| 261 | |
| 262 | Translate a socket address *sockaddr* into a 2-tuple ``(host, port)``. Depending |
| 263 | on the settings of *flags*, the result can contain a fully-qualified domain name |
| 264 | or numeric address representation in *host*. Similarly, *port* can contain a |
| 265 | string port name or a numeric port number. |
| 266 | |
| 267 | .. versionadded:: 2.2 |
| 268 | |
| 269 | |
| 270 | .. function:: getprotobyname(protocolname) |
| 271 | |
| 272 | Translate an Internet protocol name (for example, ``'icmp'``) to a constant |
| 273 | suitable for passing as the (optional) third argument to the :func:`socket` |
| 274 | function. This is usually only needed for sockets opened in "raw" mode |
| 275 | (:const:`SOCK_RAW`); for the normal socket modes, the correct protocol is chosen |
| 276 | automatically if the protocol is omitted or zero. |
| 277 | |
| 278 | |
| 279 | .. function:: getservbyname(servicename[, protocolname]) |
| 280 | |
| 281 | Translate an Internet service name and protocol name to a port number for that |
| 282 | service. The optional protocol name, if given, should be ``'tcp'`` or |
| 283 | ``'udp'``, otherwise any protocol will match. |
| 284 | |
| 285 | |
| 286 | .. function:: getservbyport(port[, protocolname]) |
| 287 | |
| 288 | Translate an Internet port number and protocol name to a service name for that |
| 289 | service. The optional protocol name, if given, should be ``'tcp'`` or |
| 290 | ``'udp'``, otherwise any protocol will match. |
| 291 | |
| 292 | |
| 293 | .. function:: socket([family[, type[, proto]]]) |
| 294 | |
| 295 | Create a new socket using the given address family, socket type and protocol |
| 296 | number. The address family should be :const:`AF_INET` (the default), |
| 297 | :const:`AF_INET6` or :const:`AF_UNIX`. The socket type should be |
| 298 | :const:`SOCK_STREAM` (the default), :const:`SOCK_DGRAM` or perhaps one of the |
| 299 | other ``SOCK_`` constants. The protocol number is usually zero and may be |
| 300 | omitted in that case. |
| 301 | |
| 302 | |
| 303 | .. function:: ssl(sock[, keyfile, certfile]) |
| 304 | |
| 305 | Initiate a SSL connection over the socket *sock*. *keyfile* is the name of a PEM |
| 306 | formatted file that contains your private key. *certfile* is a PEM formatted |
| 307 | certificate chain file. On success, a new :class:`SSLObject` is returned. |
| 308 | |
| 309 | .. warning:: |
| 310 | |
| 311 | This does not do any certificate verification! |
| 312 | |
| 313 | |
| 314 | .. function:: socketpair([family[, type[, proto]]]) |
| 315 | |
| 316 | Build a pair of connected socket objects using the given address family, socket |
| 317 | type, and protocol number. Address family, socket type, and protocol number are |
| 318 | as for the :func:`socket` function above. The default family is :const:`AF_UNIX` |
| 319 | if defined on the platform; otherwise, the default is :const:`AF_INET`. |
| 320 | Availability: Unix. |
| 321 | |
| 322 | .. versionadded:: 2.4 |
| 323 | |
| 324 | |
| 325 | .. function:: fromfd(fd, family, type[, proto]) |
| 326 | |
| 327 | Duplicate the file descriptor *fd* (an integer as returned by a file object's |
| 328 | :meth:`fileno` method) and build a socket object from the result. Address |
| 329 | family, socket type and protocol number are as for the :func:`socket` function |
| 330 | above. The file descriptor should refer to a socket, but this is not checked --- |
| 331 | subsequent operations on the object may fail if the file descriptor is invalid. |
| 332 | This function is rarely needed, but can be used to get or set socket options on |
| 333 | a socket passed to a program as standard input or output (such as a server |
| 334 | started by the Unix inet daemon). The socket is assumed to be in blocking mode. |
| 335 | Availability: Unix. |
| 336 | |
| 337 | |
| 338 | .. function:: ntohl(x) |
| 339 | |
| 340 | Convert 32-bit positive integers from network to host byte order. On machines |
| 341 | where the host byte order is the same as network byte order, this is a no-op; |
| 342 | otherwise, it performs a 4-byte swap operation. |
| 343 | |
| 344 | |
| 345 | .. function:: ntohs(x) |
| 346 | |
| 347 | Convert 16-bit positive integers from network to host byte order. On machines |
| 348 | where the host byte order is the same as network byte order, this is a no-op; |
| 349 | otherwise, it performs a 2-byte swap operation. |
| 350 | |
| 351 | |
| 352 | .. function:: htonl(x) |
| 353 | |
| 354 | Convert 32-bit positive integers from host to network byte order. On machines |
| 355 | where the host byte order is the same as network byte order, this is a no-op; |
| 356 | otherwise, it performs a 4-byte swap operation. |
| 357 | |
| 358 | |
| 359 | .. function:: htons(x) |
| 360 | |
| 361 | Convert 16-bit positive integers from host to network byte order. On machines |
| 362 | where the host byte order is the same as network byte order, this is a no-op; |
| 363 | otherwise, it performs a 2-byte swap operation. |
| 364 | |
| 365 | |
| 366 | .. function:: inet_aton(ip_string) |
| 367 | |
| 368 | Convert an IPv4 address from dotted-quad string format (for example, |
| 369 | '123.45.67.89') to 32-bit packed binary format, as a string four characters in |
| 370 | length. This is useful when conversing with a program that uses the standard C |
| 371 | library and needs objects of type :ctype:`struct in_addr`, which is the C type |
| 372 | for the 32-bit packed binary this function returns. |
| 373 | |
| 374 | If the IPv4 address string passed to this function is invalid, |
| 375 | :exc:`socket.error` will be raised. Note that exactly what is valid depends on |
| 376 | the underlying C implementation of :cfunc:`inet_aton`. |
| 377 | |
| 378 | :func:`inet_aton` does not support IPv6, and :func:`getnameinfo` should be used |
| 379 | instead for IPv4/v6 dual stack support. |
| 380 | |
| 381 | |
| 382 | .. function:: inet_ntoa(packed_ip) |
| 383 | |
| 384 | Convert a 32-bit packed IPv4 address (a string four characters in length) to its |
| 385 | standard dotted-quad string representation (for example, '123.45.67.89'). This |
| 386 | is useful when conversing with a program that uses the standard C library and |
| 387 | needs objects of type :ctype:`struct in_addr`, which is the C type for the |
| 388 | 32-bit packed binary data this function takes as an argument. |
| 389 | |
| 390 | If the string passed to this function is not exactly 4 bytes in length, |
| 391 | :exc:`socket.error` will be raised. :func:`inet_ntoa` does not support IPv6, and |
| 392 | :func:`getnameinfo` should be used instead for IPv4/v6 dual stack support. |
| 393 | |
| 394 | |
| 395 | .. function:: inet_pton(address_family, ip_string) |
| 396 | |
| 397 | Convert an IP address from its family-specific string format to a packed, binary |
| 398 | format. :func:`inet_pton` is useful when a library or network protocol calls for |
| 399 | an object of type :ctype:`struct in_addr` (similar to :func:`inet_aton`) or |
| 400 | :ctype:`struct in6_addr`. |
| 401 | |
| 402 | Supported values for *address_family* are currently :const:`AF_INET` and |
| 403 | :const:`AF_INET6`. If the IP address string *ip_string* is invalid, |
| 404 | :exc:`socket.error` will be raised. Note that exactly what is valid depends on |
| 405 | both the value of *address_family* and the underlying implementation of |
| 406 | :cfunc:`inet_pton`. |
| 407 | |
| 408 | Availability: Unix (maybe not all platforms). |
| 409 | |
| 410 | .. versionadded:: 2.3 |
| 411 | |
| 412 | |
| 413 | .. function:: inet_ntop(address_family, packed_ip) |
| 414 | |
| 415 | Convert a packed IP address (a string of some number of characters) to its |
| 416 | standard, family-specific string representation (for example, ``'7.10.0.5'`` or |
| 417 | ``'5aef:2b::8'``) :func:`inet_ntop` is useful when a library or network protocol |
| 418 | returns an object of type :ctype:`struct in_addr` (similar to :func:`inet_ntoa`) |
| 419 | or :ctype:`struct in6_addr`. |
| 420 | |
| 421 | Supported values for *address_family* are currently :const:`AF_INET` and |
| 422 | :const:`AF_INET6`. If the string *packed_ip* is not the correct length for the |
| 423 | specified address family, :exc:`ValueError` will be raised. A |
| 424 | :exc:`socket.error` is raised for errors from the call to :func:`inet_ntop`. |
| 425 | |
| 426 | Availability: Unix (maybe not all platforms). |
| 427 | |
| 428 | .. versionadded:: 2.3 |
| 429 | |
| 430 | |
| 431 | .. function:: getdefaulttimeout() |
| 432 | |
| 433 | Return the default timeout in floating seconds for new socket objects. A value |
| 434 | of ``None`` indicates that new socket objects have no timeout. When the socket |
| 435 | module is first imported, the default is ``None``. |
| 436 | |
| 437 | .. versionadded:: 2.3 |
| 438 | |
| 439 | |
| 440 | .. function:: setdefaulttimeout(timeout) |
| 441 | |
| 442 | Set the default timeout in floating seconds for new socket objects. A value of |
| 443 | ``None`` indicates that new socket objects have no timeout. When the socket |
| 444 | module is first imported, the default is ``None``. |
| 445 | |
| 446 | .. versionadded:: 2.3 |
| 447 | |
| 448 | |
| 449 | .. data:: SocketType |
| 450 | |
| 451 | This is a Python type object that represents the socket object type. It is the |
| 452 | same as ``type(socket(...))``. |
| 453 | |
| 454 | |
| 455 | .. seealso:: |
| 456 | |
| 457 | Module :mod:`SocketServer` |
| 458 | Classes that simplify writing network servers. |
| 459 | |
| 460 | |
| 461 | .. _socket-objects: |
| 462 | |
| 463 | Socket Objects |
| 464 | -------------- |
| 465 | |
| 466 | Socket objects have the following methods. Except for :meth:`makefile` these |
| 467 | correspond to Unix system calls applicable to sockets. |
| 468 | |
| 469 | |
| 470 | .. method:: socket.accept() |
| 471 | |
| 472 | Accept a connection. The socket must be bound to an address and listening for |
| 473 | connections. The return value is a pair ``(conn, address)`` where *conn* is a |
| 474 | *new* socket object usable to send and receive data on the connection, and |
| 475 | *address* is the address bound to the socket on the other end of the connection. |
| 476 | |
| 477 | |
| 478 | .. method:: socket.bind(address) |
| 479 | |
| 480 | Bind the socket to *address*. The socket must not already be bound. (The format |
| 481 | of *address* depends on the address family --- see above.) |
| 482 | |
| 483 | .. note:: |
| 484 | |
| 485 | This method has historically accepted a pair of parameters for :const:`AF_INET` |
| 486 | addresses instead of only a tuple. This was never intentional and is no longer |
| 487 | available in Python 2.0 and later. |
| 488 | |
| 489 | |
| 490 | .. method:: socket.close() |
| 491 | |
| 492 | Close the socket. All future operations on the socket object will fail. The |
| 493 | remote end will receive no more data (after queued data is flushed). Sockets are |
| 494 | automatically closed when they are garbage-collected. |
| 495 | |
| 496 | |
| 497 | .. method:: socket.connect(address) |
| 498 | |
| 499 | Connect to a remote socket at *address*. (The format of *address* depends on the |
| 500 | address family --- see above.) |
| 501 | |
| 502 | .. note:: |
| 503 | |
| 504 | This method has historically accepted a pair of parameters for :const:`AF_INET` |
| 505 | addresses instead of only a tuple. This was never intentional and is no longer |
| 506 | available in Python 2.0 and later. |
| 507 | |
| 508 | |
| 509 | .. method:: socket.connect_ex(address) |
| 510 | |
| 511 | Like ``connect(address)``, but return an error indicator instead of raising an |
| 512 | exception for errors returned by the C-level :cfunc:`connect` call (other |
| 513 | problems, such as "host not found," can still raise exceptions). The error |
| 514 | indicator is ``0`` if the operation succeeded, otherwise the value of the |
| 515 | :cdata:`errno` variable. This is useful to support, for example, asynchronous |
| 516 | connects. |
| 517 | |
| 518 | .. note:: |
| 519 | |
| 520 | This method has historically accepted a pair of parameters for :const:`AF_INET` |
| 521 | addresses instead of only a tuple. This was never intentional and is no longer |
| 522 | available in Python 2.0 and later. |
| 523 | |
| 524 | |
| 525 | .. method:: socket.fileno() |
| 526 | |
| 527 | Return the socket's file descriptor (a small integer). This is useful with |
| 528 | :func:`select.select`. |
| 529 | |
| 530 | Under Windows the small integer returned by this method cannot be used where a |
| 531 | file descriptor can be used (such as :func:`os.fdopen`). Unix does not have |
| 532 | this limitation. |
| 533 | |
| 534 | |
| 535 | .. method:: socket.getpeername() |
| 536 | |
| 537 | Return the remote address to which the socket is connected. This is useful to |
| 538 | find out the port number of a remote IPv4/v6 socket, for instance. (The format |
| 539 | of the address returned depends on the address family --- see above.) On some |
| 540 | systems this function is not supported. |
| 541 | |
| 542 | |
| 543 | .. method:: socket.getsockname() |
| 544 | |
| 545 | Return the socket's own address. This is useful to find out the port number of |
| 546 | an IPv4/v6 socket, for instance. (The format of the address returned depends on |
| 547 | the address family --- see above.) |
| 548 | |
| 549 | |
| 550 | .. method:: socket.getsockopt(level, optname[, buflen]) |
| 551 | |
| 552 | Return the value of the given socket option (see the Unix man page |
| 553 | :manpage:`getsockopt(2)`). The needed symbolic constants (:const:`SO_\*` etc.) |
| 554 | are defined in this module. If *buflen* is absent, an integer option is assumed |
| 555 | and its integer value is returned by the function. If *buflen* is present, it |
| 556 | specifies the maximum length of the buffer used to receive the option in, and |
| 557 | this buffer is returned as a string. It is up to the caller to decode the |
| 558 | contents of the buffer (see the optional built-in module :mod:`struct` for a way |
| 559 | to decode C structures encoded as strings). |
| 560 | |
| 561 | |
| 562 | .. method:: socket.listen(backlog) |
| 563 | |
| 564 | Listen for connections made to the socket. The *backlog* argument specifies the |
| 565 | maximum number of queued connections and should be at least 1; the maximum value |
| 566 | is system-dependent (usually 5). |
| 567 | |
| 568 | |
| 569 | .. method:: socket.makefile([mode[, bufsize]]) |
| 570 | |
| 571 | .. index:: single: I/O control; buffering |
| 572 | |
| 573 | Return a :dfn:`file object` associated with the socket. (File objects are |
| 574 | described in :ref:`bltin-file-objects`.) The file object |
| 575 | references a :cfunc:`dup`\ ped version of the socket file descriptor, so the |
| 576 | file object and socket object may be closed or garbage-collected independently. |
| 577 | The socket must be in blocking mode (it can not have a timeout). The optional |
| 578 | *mode* and *bufsize* arguments are interpreted the same way as by the built-in |
| 579 | :func:`file` function; see :ref:`built-in-funcs` for more information. |
| 580 | |
| 581 | |
| 582 | .. method:: socket.recv(bufsize[, flags]) |
| 583 | |
| 584 | Receive data from the socket. The return value is a string representing the |
| 585 | data received. The maximum amount of data to be received at once is specified |
| 586 | by *bufsize*. See the Unix manual page :manpage:`recv(2)` for the meaning of |
| 587 | the optional argument *flags*; it defaults to zero. |
| 588 | |
| 589 | .. note:: |
| 590 | |
| 591 | For best match with hardware and network realities, the value of *bufsize* |
| 592 | should be a relatively small power of 2, for example, 4096. |
| 593 | |
| 594 | |
| 595 | .. method:: socket.recvfrom(bufsize[, flags]) |
| 596 | |
| 597 | Receive data from the socket. The return value is a pair ``(string, address)`` |
| 598 | where *string* is a string representing the data received and *address* is the |
| 599 | address of the socket sending the data. See the Unix manual page |
| 600 | :manpage:`recv(2)` for the meaning of the optional argument *flags*; it defaults |
| 601 | to zero. (The format of *address* depends on the address family --- see above.) |
| 602 | |
| 603 | |
| 604 | .. method:: socket.recvfrom_into(buffer[, nbytes[, flags]]) |
| 605 | |
| 606 | Receive data from the socket, writing it into *buffer* instead of creating a |
| 607 | new string. The return value is a pair ``(nbytes, address)`` where *nbytes* is |
| 608 | the number of bytes received and *address* is the address of the socket sending |
| 609 | the data. See the Unix manual page :manpage:`recv(2)` for the meaning of the |
| 610 | optional argument *flags*; it defaults to zero. (The format of *address* |
| 611 | depends on the address family --- see above.) |
| 612 | |
| 613 | .. versionadded:: 2.5 |
| 614 | |
| 615 | |
| 616 | .. method:: socket.recv_into(buffer[, nbytes[, flags]]) |
| 617 | |
| 618 | Receive up to *nbytes* bytes from the socket, storing the data into a buffer |
| 619 | rather than creating a new string. If *nbytes* is not specified (or 0), |
| 620 | receive up to the size available in the given buffer. See the Unix manual page |
| 621 | :manpage:`recv(2)` for the meaning of the optional argument *flags*; it defaults |
| 622 | to zero. |
| 623 | |
| 624 | .. versionadded:: 2.5 |
| 625 | |
| 626 | |
| 627 | .. method:: socket.send(string[, flags]) |
| 628 | |
| 629 | Send data to the socket. The socket must be connected to a remote socket. The |
| 630 | optional *flags* argument has the same meaning as for :meth:`recv` above. |
| 631 | Returns the number of bytes sent. Applications are responsible for checking that |
| 632 | all data has been sent; if only some of the data was transmitted, the |
| 633 | application needs to attempt delivery of the remaining data. |
| 634 | |
| 635 | |
| 636 | .. method:: socket.sendall(string[, flags]) |
| 637 | |
| 638 | Send data to the socket. The socket must be connected to a remote socket. The |
| 639 | optional *flags* argument has the same meaning as for :meth:`recv` above. |
| 640 | Unlike :meth:`send`, this method continues to send data from *string* until |
| 641 | either all data has been sent or an error occurs. ``None`` is returned on |
| 642 | success. On error, an exception is raised, and there is no way to determine how |
| 643 | much data, if any, was successfully sent. |
| 644 | |
| 645 | |
| 646 | .. method:: socket.sendto(string[, flags], address) |
| 647 | |
| 648 | Send data to the socket. The socket should not be connected to a remote socket, |
| 649 | since the destination socket is specified by *address*. The optional *flags* |
| 650 | argument has the same meaning as for :meth:`recv` above. Return the number of |
| 651 | bytes sent. (The format of *address* depends on the address family --- see |
| 652 | above.) |
| 653 | |
| 654 | |
| 655 | .. method:: socket.setblocking(flag) |
| 656 | |
| 657 | Set blocking or non-blocking mode of the socket: if *flag* is 0, the socket is |
| 658 | set to non-blocking, else to blocking mode. Initially all sockets are in |
| 659 | blocking mode. In non-blocking mode, if a :meth:`recv` call doesn't find any |
| 660 | data, or if a :meth:`send` call can't immediately dispose of the data, a |
| 661 | :exc:`error` exception is raised; in blocking mode, the calls block until they |
| 662 | can proceed. ``s.setblocking(0)`` is equivalent to ``s.settimeout(0)``; |
| 663 | ``s.setblocking(1)`` is equivalent to ``s.settimeout(None)``. |
| 664 | |
| 665 | |
| 666 | .. method:: socket.settimeout(value) |
| 667 | |
| 668 | Set a timeout on blocking socket operations. The *value* argument can be a |
| 669 | nonnegative float expressing seconds, or ``None``. If a float is given, |
| 670 | subsequent socket operations will raise an :exc:`timeout` exception if the |
| 671 | timeout period *value* has elapsed before the operation has completed. Setting |
| 672 | a timeout of ``None`` disables timeouts on socket operations. |
| 673 | ``s.settimeout(0.0)`` is equivalent to ``s.setblocking(0)``; |
| 674 | ``s.settimeout(None)`` is equivalent to ``s.setblocking(1)``. |
| 675 | |
| 676 | .. versionadded:: 2.3 |
| 677 | |
| 678 | |
| 679 | .. method:: socket.gettimeout() |
| 680 | |
| 681 | Return the timeout in floating seconds associated with socket operations, or |
| 682 | ``None`` if no timeout is set. This reflects the last call to |
| 683 | :meth:`setblocking` or :meth:`settimeout`. |
| 684 | |
| 685 | .. versionadded:: 2.3 |
| 686 | |
| 687 | Some notes on socket blocking and timeouts: A socket object can be in one of |
| 688 | three modes: blocking, non-blocking, or timeout. Sockets are always created in |
| 689 | blocking mode. In blocking mode, operations block until complete. In |
| 690 | non-blocking mode, operations fail (with an error that is unfortunately |
| 691 | system-dependent) if they cannot be completed immediately. In timeout mode, |
| 692 | operations fail if they cannot be completed within the timeout specified for the |
| 693 | socket. The :meth:`setblocking` method is simply a shorthand for certain |
| 694 | :meth:`settimeout` calls. |
| 695 | |
| 696 | Timeout mode internally sets the socket in non-blocking mode. The blocking and |
| 697 | timeout modes are shared between file descriptors and socket objects that refer |
| 698 | to the same network endpoint. A consequence of this is that file objects |
| 699 | returned by the :meth:`makefile` method must only be used when the socket is in |
| 700 | blocking mode; in timeout or non-blocking mode file operations that cannot be |
| 701 | completed immediately will fail. |
| 702 | |
| 703 | Note that the :meth:`connect` operation is subject to the timeout setting, and |
| 704 | in general it is recommended to call :meth:`settimeout` before calling |
| 705 | :meth:`connect`. |
| 706 | |
| 707 | |
| 708 | .. method:: socket.setsockopt(level, optname, value) |
| 709 | |
| 710 | .. index:: module: struct |
| 711 | |
| 712 | Set the value of the given socket option (see the Unix manual page |
| 713 | :manpage:`setsockopt(2)`). The needed symbolic constants are defined in the |
| 714 | :mod:`socket` module (:const:`SO_\*` etc.). The value can be an integer or a |
| 715 | string representing a buffer. In the latter case it is up to the caller to |
| 716 | ensure that the string contains the proper bits (see the optional built-in |
| 717 | module :mod:`struct` for a way to encode C structures as strings). |
| 718 | |
| 719 | |
| 720 | .. method:: socket.shutdown(how) |
| 721 | |
| 722 | Shut down one or both halves of the connection. If *how* is :const:`SHUT_RD`, |
| 723 | further receives are disallowed. If *how* is :const:`SHUT_WR`, further sends |
| 724 | are disallowed. If *how* is :const:`SHUT_RDWR`, further sends and receives are |
| 725 | disallowed. |
| 726 | |
| 727 | Note that there are no methods :meth:`read` or :meth:`write`; use :meth:`recv` |
| 728 | and :meth:`send` without *flags* argument instead. |
| 729 | |
| 730 | Socket objects also have these (read-only) attributes that correspond to the |
| 731 | values given to the :class:`socket` constructor. |
| 732 | |
| 733 | |
| 734 | .. attribute:: socket.family |
| 735 | |
| 736 | The socket family. |
| 737 | |
| 738 | .. versionadded:: 2.5 |
| 739 | |
| 740 | |
| 741 | .. attribute:: socket.type |
| 742 | |
| 743 | The socket type. |
| 744 | |
| 745 | .. versionadded:: 2.5 |
| 746 | |
| 747 | |
| 748 | .. attribute:: socket.proto |
| 749 | |
| 750 | The socket protocol. |
| 751 | |
| 752 | .. versionadded:: 2.5 |
| 753 | |
| 754 | |
| 755 | .. _ssl-objects: |
| 756 | |
| 757 | SSL Objects |
| 758 | ----------- |
| 759 | |
| 760 | SSL objects have the following methods. |
| 761 | |
| 762 | |
| 763 | .. method:: SSL.write(s) |
| 764 | |
| 765 | Writes the string *s* to the on the object's SSL connection. The return value is |
| 766 | the number of bytes written. |
| 767 | |
| 768 | |
| 769 | .. method:: SSL.read([n]) |
| 770 | |
| 771 | If *n* is provided, read *n* bytes from the SSL connection, otherwise read until |
| 772 | EOF. The return value is a string of the bytes read. |
| 773 | |
| 774 | |
| 775 | .. method:: SSL.server() |
| 776 | |
| 777 | Returns a string describing the server's certificate. Useful for debugging |
| 778 | purposes; do not parse the content of this string because its format can't be |
| 779 | parsed unambiguously. |
| 780 | |
| 781 | |
| 782 | .. method:: SSL.issuer() |
| 783 | |
| 784 | Returns a string describing the issuer of the server's certificate. Useful for |
| 785 | debugging purposes; do not parse the content of this string because its format |
| 786 | can't be parsed unambiguously. |
| 787 | |
| 788 | |
| 789 | .. _socket-example: |
| 790 | |
| 791 | Example |
| 792 | ------- |
| 793 | |
| 794 | Here are four minimal example programs using the TCP/IP protocol: a server that |
| 795 | echoes all data that it receives back (servicing only one client), and a client |
| 796 | using it. Note that a server must perform the sequence :func:`socket`, |
| 797 | :meth:`bind`, :meth:`listen`, :meth:`accept` (possibly repeating the |
| 798 | :meth:`accept` to service more than one client), while a client only needs the |
| 799 | sequence :func:`socket`, :meth:`connect`. Also note that the server does not |
| 800 | :meth:`send`/:meth:`recv` on the socket it is listening on but on the new |
| 801 | socket returned by :meth:`accept`. |
| 802 | |
| 803 | The first two examples support IPv4 only. :: |
| 804 | |
| 805 | # Echo server program |
| 806 | import socket |
| 807 | |
| 808 | HOST = '' # Symbolic name meaning the local host |
| 809 | PORT = 50007 # Arbitrary non-privileged port |
| 810 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 811 | s.bind((HOST, PORT)) |
| 812 | s.listen(1) |
| 813 | conn, addr = s.accept() |
| 814 | print 'Connected by', addr |
| 815 | while 1: |
| 816 | data = conn.recv(1024) |
| 817 | if not data: break |
| 818 | conn.send(data) |
| 819 | conn.close() |
| 820 | |
| 821 | :: |
| 822 | |
| 823 | # Echo client program |
| 824 | import socket |
| 825 | |
| 826 | HOST = 'daring.cwi.nl' # The remote host |
| 827 | PORT = 50007 # The same port as used by the server |
| 828 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 829 | s.connect((HOST, PORT)) |
| 830 | s.send('Hello, world') |
| 831 | data = s.recv(1024) |
| 832 | s.close() |
| 833 | print 'Received', repr(data) |
| 834 | |
| 835 | The next two examples are identical to the above two, but support both IPv4 and |
| 836 | IPv6. The server side will listen to the first address family available (it |
| 837 | should listen to both instead). On most of IPv6-ready systems, IPv6 will take |
| 838 | precedence and the server may not accept IPv4 traffic. The client side will try |
| 839 | to connect to the all addresses returned as a result of the name resolution, and |
| 840 | sends traffic to the first one connected successfully. :: |
| 841 | |
| 842 | # Echo server program |
| 843 | import socket |
| 844 | import sys |
| 845 | |
| 846 | HOST = '' # Symbolic name meaning the local host |
| 847 | PORT = 50007 # Arbitrary non-privileged port |
| 848 | s = None |
| 849 | for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE): |
| 850 | af, socktype, proto, canonname, sa = res |
| 851 | try: |
| 852 | s = socket.socket(af, socktype, proto) |
| 853 | except socket.error as msg: |
| 854 | s = None |
| 855 | continue |
| 856 | try: |
| 857 | s.bind(sa) |
| 858 | s.listen(1) |
| 859 | except socket.error as msg: |
| 860 | s.close() |
| 861 | s = None |
| 862 | continue |
| 863 | break |
| 864 | if s is None: |
| 865 | print 'could not open socket' |
| 866 | sys.exit(1) |
| 867 | conn, addr = s.accept() |
| 868 | print 'Connected by', addr |
| 869 | while 1: |
| 870 | data = conn.recv(1024) |
| 871 | if not data: break |
| 872 | conn.send(data) |
| 873 | conn.close() |
| 874 | |
| 875 | :: |
| 876 | |
| 877 | # Echo client program |
| 878 | import socket |
| 879 | import sys |
| 880 | |
| 881 | HOST = 'daring.cwi.nl' # The remote host |
| 882 | PORT = 50007 # The same port as used by the server |
| 883 | s = None |
| 884 | for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM): |
| 885 | af, socktype, proto, canonname, sa = res |
| 886 | try: |
| 887 | s = socket.socket(af, socktype, proto) |
| 888 | except socket.error as msg: |
| 889 | s = None |
| 890 | continue |
| 891 | try: |
| 892 | s.connect(sa) |
| 893 | except socket.error as msg: |
| 894 | s.close() |
| 895 | s = None |
| 896 | continue |
| 897 | break |
| 898 | if s is None: |
| 899 | print 'could not open socket' |
| 900 | sys.exit(1) |
| 901 | s.send('Hello, world') |
| 902 | data = s.recv(1024) |
| 903 | s.close() |
| 904 | print 'Received', repr(data) |
| 905 | |
| 906 | This example connects to an SSL server, prints the server and issuer's |
| 907 | distinguished names, sends some bytes, and reads part of the response:: |
| 908 | |
| 909 | import socket |
| 910 | |
| 911 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 912 | s.connect(('www.verisign.com', 443)) |
| 913 | |
| 914 | ssl_sock = socket.ssl(s) |
| 915 | |
| 916 | print repr(ssl_sock.server()) |
| 917 | print repr(ssl_sock.issuer()) |
| 918 | |
| 919 | # Set a simple HTTP request -- use httplib in actual code. |
| 920 | ssl_sock.write("""GET / HTTP/1.0\r |
| 921 | Host: www.verisign.com\r\n\r\n""") |
| 922 | |
| 923 | # Read a chunk of data. Will not necessarily |
| 924 | # read all the data returned by the server. |
| 925 | data = ssl_sock.read() |
| 926 | |
| 927 | # Note that you need to close the underlying socket, not the SSL object. |
| 928 | del ssl_sock |
| 929 | s.close() |
| 930 | |
| 931 | At this writing, this SSL example prints the following output (line breaks |
| 932 | inserted for readability):: |
| 933 | |
| 934 | '/C=US/ST=California/L=Mountain View/ |
| 935 | O=VeriSign, Inc./OU=Production Services/ |
| 936 | OU=Terms of use at www.verisign.com/rpa (c)00/ |
| 937 | CN=www.verisign.com' |
| 938 | '/O=VeriSign Trust Network/OU=VeriSign, Inc./ |
| 939 | OU=VeriSign International Server CA - Class 3/ |
| 940 | OU=www.verisign.com/CPS Incorp.by Ref. LIABILITY LTD.(c)97 VeriSign' |
| 941 | |