Changeset 391 for python/trunk/Doc/library/socket.rst
- Timestamp:
- Mar 19, 2014, 11:31:01 PM (11 years ago)
- Location:
- python/trunk
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
python/trunk
-
Property svn:mergeinfo
set to
/python/vendor/Python-2.7.6 merged eligible /python/vendor/current merged eligible
-
Property svn:mergeinfo
set to
-
python/trunk/Doc/library/socket.rst
r2 r391 1 2 1 :mod:`socket` --- Low-level networking interface 3 2 ================================================ … … 30 29 The Python interface is a straightforward transliteration of the Unix system 31 30 call and library interface for sockets to Python's object-oriented style: the 32 :func:` socket` function returns a :dfn:`socket object` whose methods implement31 :func:`.socket` function returns a :dfn:`socket object` whose methods implement 33 32 the various socket system calls. Parameter types are somewhat higher-level than 34 33 in the C interface: as with :meth:`read` and :meth:`write` operations on Python … … 40 39 :const:`AF_INET` address family, where *host* is a string representing either a 41 40 hostname in Internet domain notation like ``'daring.cwi.nl'`` or an IPv4 address 42 like ``'100.50.200.5'``, and *port* is an integ ral port number. For41 like ``'100.50.200.5'``, and *port* is an integer. For 43 42 :const:`AF_INET6` address family, a four-tuple ``(host, port, flowinfo, 44 43 scopeid)`` is used, where *flowinfo* and *scopeid* represents ``sin6_flowinfo`` … … 74 73 ``(addr_type, v1, v2, v3 [, scope])``, where: 75 74 76 - *addr_type* is one of TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, or77 TIPC_ADDR_ID.78 - *scope* is one of TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and79 TIPC_NODE_SCOPE.80 - If *addr_type* is TIPC_ADDR_NAME, then *v1* is the server type, *v2* is81 82 83 If *addr_type* is TIPC_ADDR_NAMESEQ, then *v1* is the server type, *v2*84 85 86 If *addr_type* is TIPC_ADDR_ID, then *v1* is the node, *v2* is the87 75 - *addr_type* is one of :const:`TIPC_ADDR_NAMESEQ`, :const:`TIPC_ADDR_NAME`, 76 or :const:`TIPC_ADDR_ID`. 77 - *scope* is one of :const:`TIPC_ZONE_SCOPE`, :const:`TIPC_CLUSTER_SCOPE`, 78 and :const:`TIPC_NODE_SCOPE`. 79 - If *addr_type* is :const:`TIPC_ADDR_NAME`, then *v1* is the server type, *v2* is 80 the port identifier, and *v3* should be 0. 81 82 If *addr_type* is :const:`TIPC_ADDR_NAMESEQ`, then *v1* is the server type, *v2* 83 is the lower port number, and *v3* is the upper port number. 84 85 If *addr_type* is :const:`TIPC_ADDR_ID`, then *v1* is the node, *v2* is the 86 reference, and *v3* should be set to 0. 88 87 89 88 … … 92 91 semantics raise the error :exc:`socket.error`. 93 92 94 Non-blocking mode is supported through :meth:`setblocking`. A generalization of 95 this based on timeouts is supported through :meth:`settimeout`. 93 Non-blocking mode is supported through :meth:`~socket.setblocking`. A 94 generalization of this based on timeouts is supported through 95 :meth:`~socket.settimeout`. 96 96 97 97 The module :mod:`socket` exports the following constants and functions: … … 120 120 The accompanying value is a pair ``(h_errno, string)`` representing an error 121 121 returned by a library call. *string* represents the description of *h_errno*, as 122 returned by the :c func:`hstrerror` C function.122 returned by the :c:func:`hstrerror` C function. 123 123 124 124 … … 128 128 :func:`getnameinfo`. The accompanying value is a pair ``(error, string)`` 129 129 representing an error returned by a library call. *string* represents the 130 description of *error*, as returned by the :c func:`gai_strerror` C function. The130 description of *error*, as returned by the :c:func:`gai_strerror` C function. The 131 131 *error* value will match one of the :const:`EAI_\*` constants defined in this 132 132 module. … … 147 147 148 148 These constants represent the address (and protocol) families, used for the 149 first argument to :func:` socket`. If the :const:`AF_UNIX` constant is not149 first argument to :func:`.socket`. If the :const:`AF_UNIX` constant is not 150 150 defined then this protocol is unsupported. 151 151 … … 187 187 188 188 Constants for Windows' WSAIoctl(). The constants are used as arguments to the 189 :meth:` ioctl` method of socket objects.189 :meth:`~socket.socket.ioctl` method of socket objects. 190 190 191 191 .. versionadded:: 2.6 … … 206 206 207 207 208 .. function:: create_connection(address[, timeout]) 209 210 Convenience function. Connect to *address* (a 2-tuple ``(host, port)``), 211 and return the socket object. Passing the optional *timeout* parameter will 212 set the timeout on the socket instance before attempting to connect. If no 213 *timeout* is supplied, the global default timeout setting returned by 208 .. function:: create_connection(address[, timeout[, source_address]]) 209 210 Connect to a TCP service listening on the Internet *address* (a 2-tuple 211 ``(host, port)``), and return the socket object. This is a higher-level 212 function than :meth:`socket.connect`: if *host* is a non-numeric hostname, 213 it will try to resolve it for both :data:`AF_INET` and :data:`AF_INET6`, 214 and then try to connect to all possible addresses in turn until a 215 connection succeeds. This makes it easy to write clients that are 216 compatible to both IPv4 and IPv6. 217 218 Passing the optional *timeout* parameter will set the timeout on the 219 socket instance before attempting to connect. If no *timeout* is 220 supplied, the global default timeout setting returned by 214 221 :func:`getdefaulttimeout` is used. 215 222 223 If supplied, *source_address* must be a 2-tuple ``(host, port)`` for the 224 socket to bind to as its source address before connecting. If host or port 225 are '' or 0 respectively the OS default behavior will be used. 226 216 227 .. versionadded:: 2.6 217 228 229 .. versionchanged:: 2.7 230 *source_address* was added. 231 218 232 219 233 .. function:: getaddrinfo(host, port[, family[, socktype[, proto[, flags]]]]) 220 234 221 Resolves the *host*/*port* argument, into a sequence of 5-tuples that contain 222 all the necessary arguments for creating the corresponding socket. *host* is a domain 223 name, a string representation of an IPv4/v6 address or ``None``. *port* is a string 224 service name such as ``'http'``, a numeric port number or ``None``. 225 The rest of the arguments are optional and must be numeric if specified. 226 By passing ``None`` as the value of *host* and *port*, , you can pass ``NULL`` to the C API. 227 228 The :func:`getaddrinfo` function returns a list of 5-tuples with the following 229 structure: 235 Translate the *host*/*port* argument into a sequence of 5-tuples that contain 236 all the necessary arguments for creating a socket connected to that service. 237 *host* is a domain name, a string representation of an IPv4/v6 address 238 or ``None``. *port* is a string service name such as ``'http'``, a numeric 239 port number or ``None``. By passing ``None`` as the value of *host* 240 and *port*, you can pass ``NULL`` to the underlying C API. 241 242 The *family*, *socktype* and *proto* arguments can be optionally specified 243 in order to narrow the list of addresses returned. By default, their value 244 is ``0``, meaning that the full range of results is selected. 245 The *flags* argument can be one or several of the ``AI_*`` constants, 246 and will influence how results are computed and returned. Its default value 247 is ``0``. For example, :const:`AI_NUMERICHOST` will disable domain name 248 resolution and will raise an error if *host* is a domain name. 249 250 The function returns a list of 5-tuples with the following structure: 230 251 231 252 ``(family, socktype, proto, canonname, sockaddr)`` 232 253 233 *family*, *socktype*, *proto* are all integers and are meant to be passed to the 234 :func:`socket` function. *canonname* is a string representing the canonical name 235 of the *host*. It can be a numeric IPv4/v6 address when :const:`AI_CANONNAME` is 236 specified for a numeric *host*. *sockaddr* is a tuple describing a socket 237 address, as described above. See the source for :mod:`socket` and other 238 library modules for a typical usage of the function. 254 In these tuples, *family*, *socktype*, *proto* are all integers and are 255 meant to be passed to the :func:`.socket` function. *canonname* will be 256 a string representing the canonical name of the *host* if 257 :const:`AI_CANONNAME` is part of the *flags* argument; else *canonname* 258 will be empty. *sockaddr* is a tuple describing a socket address, whose 259 format depends on the returned *family* (a ``(address, port)`` 2-tuple for 260 :const:`AF_INET`, a ``(address, port, flow info, scope id)`` 4-tuple for 261 :const:`AF_INET6`), and is meant to be passed to the :meth:`socket.connect` 262 method. 263 264 The following example fetches address information for a hypothetical TCP 265 connection to ``www.python.org`` on port 80 (results may differ on your 266 system if IPv6 isn't enabled):: 267 268 >>> socket.getaddrinfo("www.python.org", 80, 0, 0, socket.SOL_TCP) 269 [(2, 1, 6, '', ('82.94.164.162', 80)), 270 (10, 1, 6, '', ('2001:888:2000:d::a2', 80, 0, 0))] 239 271 240 272 .. versionadded:: 2.2 … … 312 344 313 345 Translate an Internet protocol name (for example, ``'icmp'``) to a constant 314 suitable for passing as the (optional) third argument to the :func:` socket`346 suitable for passing as the (optional) third argument to the :func:`.socket` 315 347 function. This is usually only needed for sockets opened in "raw" mode 316 348 (:const:`SOCK_RAW`); for the normal socket modes, the correct protocol is chosen … … 346 378 Build a pair of connected socket objects using the given address family, socket 347 379 type, and protocol number. Address family, socket type, and protocol number are 348 as for the :func:` socket` function above. The default family is :const:`AF_UNIX`380 as for the :func:`.socket` function above. The default family is :const:`AF_UNIX` 349 381 if defined on the platform; otherwise, the default is :const:`AF_INET`. 350 382 Availability: Unix. … … 357 389 Duplicate the file descriptor *fd* (an integer as returned by a file object's 358 390 :meth:`fileno` method) and build a socket object from the result. Address 359 family, socket type and protocol number are as for the :func:` socket` function391 family, socket type and protocol number are as for the :func:`.socket` function 360 392 above. The file descriptor should refer to a socket, but this is not checked --- 361 393 subsequent operations on the object may fail if the file descriptor is invalid. … … 399 431 '123.45.67.89') to 32-bit packed binary format, as a string four characters in 400 432 length. This is useful when conversing with a program that uses the standard C 401 library and needs objects of type :c type:`struct in_addr`, which is the C type433 library and needs objects of type :c:type:`struct in_addr`, which is the C type 402 434 for the 32-bit packed binary this function returns. 403 435 … … 407 439 If the IPv4 address string passed to this function is invalid, 408 440 :exc:`socket.error` will be raised. Note that exactly what is valid depends on 409 the underlying C implementation of :c func:`inet_aton`.441 the underlying C implementation of :c:func:`inet_aton`. 410 442 411 443 :func:`inet_aton` does not support IPv6, and :func:`inet_pton` should be used … … 418 450 standard dotted-quad string representation (for example, '123.45.67.89'). This 419 451 is useful when conversing with a program that uses the standard C library and 420 needs objects of type :c type:`struct in_addr`, which is the C type for the452 needs objects of type :c:type:`struct in_addr`, which is the C type for the 421 453 32-bit packed binary data this function takes as an argument. 422 454 … … 430 462 Convert an IP address from its family-specific string format to a packed, binary 431 463 format. :func:`inet_pton` is useful when a library or network protocol calls for 432 an object of type :c type:`struct in_addr` (similar to :func:`inet_aton`) or433 :c type:`struct in6_addr`.464 an object of type :c:type:`struct in_addr` (similar to :func:`inet_aton`) or 465 :c:type:`struct in6_addr`. 434 466 435 467 Supported values for *address_family* are currently :const:`AF_INET` and … … 437 469 :exc:`socket.error` will be raised. Note that exactly what is valid depends on 438 470 both the value of *address_family* and the underlying implementation of 439 :c func:`inet_pton`.471 :c:func:`inet_pton`. 440 472 441 473 Availability: Unix (maybe not all platforms). … … 449 481 standard, family-specific string representation (for example, ``'7.10.0.5'`` or 450 482 ``'5aef:2b::8'``) :func:`inet_ntop` is useful when a library or network protocol 451 returns an object of type :c type:`struct in_addr` (similar to :func:`inet_ntoa`)452 or :c type:`struct in6_addr`.483 returns an object of type :c:type:`struct in_addr` (similar to :func:`inet_ntoa`) 484 or :c:type:`struct in6_addr`. 453 485 454 486 Supported values for *address_family* are currently :const:`AF_INET` and … … 464 496 .. function:: getdefaulttimeout() 465 497 466 Return the default timeout in floating secondsfor new socket objects. A value498 Return the default timeout in seconds (float) for new socket objects. A value 467 499 of ``None`` indicates that new socket objects have no timeout. When the socket 468 500 module is first imported, the default is ``None``. … … 473 505 .. function:: setdefaulttimeout(timeout) 474 506 475 Set the default timeout in floating secondsfor new socket objects. A value of507 Set the default timeout in seconds (float) for new socket objects. A value of 476 508 ``None`` indicates that new socket objects have no timeout. When the socket 477 509 module is first imported, the default is ``None``. … … 490 522 Module :mod:`SocketServer` 491 523 Classes that simplify writing network servers. 524 525 Module :mod:`ssl` 526 A TLS/SSL wrapper for socket objects. 492 527 493 528 … … 527 562 automatically closed when they are garbage-collected. 528 563 564 .. note:: 565 :meth:`close()` releases the resource associated with a connection but 566 does not necessarily close the connection immediately. If you want 567 to close the connection in a timely fashion, call :meth:`shutdown()` 568 before :meth:`close()`. 569 529 570 530 571 .. method:: socket.connect(address) … … 543 584 544 585 Like ``connect(address)``, but return an error indicator instead of raising an 545 exception for errors returned by the C-level :c func:`connect` call (other586 exception for errors returned by the C-level :c:func:`connect` call (other 546 587 problems, such as "host not found," can still raise exceptions). The error 547 588 indicator is ``0`` if the operation succeeded, otherwise the value of the 548 :c data:`errno` variable. This is useful to support, for example, asynchronous589 :c:data:`errno` variable. This is useful to support, for example, asynchronous 549 590 connects. 550 591 … … 598 639 599 640 The :meth:`ioctl` method is a limited interface to the WSAIoctl system 600 interface. Please refer to the MSDN documentation for more information. 641 interface. Please refer to the `Win32 documentation 642 <http://msdn.microsoft.com/en-us/library/ms741621%28VS.85%29.aspx>`_ for more 643 information. 601 644 602 645 On other platforms, the generic :func:`fcntl.fcntl` and :func:`fcntl.ioctl` … … 609 652 610 653 Listen for connections made to the socket. The *backlog* argument specifies the 611 maximum number of queued connections and should be at least 1; the maximum value612 is system-dependent (usually 5) .654 maximum number of queued connections and should be at least 0; the maximum value 655 is system-dependent (usually 5), the minimum value is forced to 0. 613 656 614 657 … … 619 662 Return a :dfn:`file object` associated with the socket. (File objects are 620 663 described in :ref:`bltin-file-objects`.) The file object 621 references a :c func:`dup`\ ped version of the socket file descriptor, so the664 references a :c:func:`dup`\ ped version of the socket file descriptor, so the 622 665 file object and socket object may be closed or garbage-collected independently. 623 666 The socket must be in blocking mode (it can not have a timeout). The optional 624 667 *mode* and *bufsize* arguments are interpreted the same way as by the built-in 625 668 :func:`file` function. 669 670 .. note:: 671 672 On Windows, the file-like object created by :meth:`makefile` cannot be 673 used where a file object with a file descriptor is expected, such as the 674 stream arguments of :meth:`subprocess.Popen`. 626 675 627 676 … … 663 712 664 713 Receive up to *nbytes* bytes from the socket, storing the data into a buffer 665 rather than creating a new string. 666 receive up to the size available in the given buffer. See the Unix manual page667 :manpage:`recv(2)` for the meaning of the optional argument *flags*; it defaults668 to zero.714 rather than creating a new string. If *nbytes* is not specified (or 0), 715 receive up to the size available in the given buffer. Returns the number of 716 bytes received. See the Unix manual page :manpage:`recv(2)` for the meaning 717 of the optional argument *flags*; it defaults to zero. 669 718 670 719 .. versionadded:: 2.5 … … 677 726 Returns the number of bytes sent. Applications are responsible for checking that 678 727 all data has been sent; if only some of the data was transmitted, the 679 application needs to attempt delivery of the remaining data. 728 application needs to attempt delivery of the remaining data. For further 729 information on this concept, consult the :ref:`socket-howto`. 680 730 681 731 … … 690 740 691 741 692 .. method:: socket.sendto(string[, flags], address) 742 .. method:: socket.sendto(string, address) 743 socket.sendto(string, flags, address) 693 744 694 745 Send data to the socket. The socket should not be connected to a remote socket, … … 706 757 data, or if a :meth:`send` call can't immediately dispose of the data, a 707 758 :exc:`error` exception is raised; in blocking mode, the calls block until they 708 can proceed. ``s.setblocking(0)`` is equivalent to ``s.settimeout(0 )``;759 can proceed. ``s.setblocking(0)`` is equivalent to ``s.settimeout(0.0)``; 709 760 ``s.setblocking(1)`` is equivalent to ``s.settimeout(None)``. 710 761 … … 714 765 Set a timeout on blocking socket operations. The *value* argument can be a 715 766 nonnegative float expressing seconds, or ``None``. If a float is given, 716 subsequent socket operations will raise a n:exc:`timeout` exception if the767 subsequent socket operations will raise a :exc:`timeout` exception if the 717 768 timeout period *value* has elapsed before the operation has completed. Setting 718 769 a timeout of ``None`` disables timeouts on socket operations. … … 725 776 .. method:: socket.gettimeout() 726 777 727 Return the timeout in floating secondsassociated with socket operations, or778 Return the timeout in seconds (float) associated with socket operations, or 728 779 ``None`` if no timeout is set. This reflects the last call to 729 780 :meth:`setblocking` or :meth:`settimeout`. … … 738 789 system-dependent) if they cannot be completed immediately. In timeout mode, 739 790 operations fail if they cannot be completed within the timeout specified for the 740 socket or if the system returns an error. The :meth:` setblocking` method is simply741 a shorthand for certain :meth:`settimeout` calls.791 socket or if the system returns an error. The :meth:`~socket.setblocking` 792 method is simply a shorthand for certain :meth:`~socket.settimeout` calls. 742 793 743 794 Timeout mode internally sets the socket in non-blocking mode. The blocking and 744 795 timeout modes are shared between file descriptors and socket objects that refer 745 796 to the same network endpoint. A consequence of this is that file objects 746 returned by the :meth:` makefile` method must only be used when the socket is in747 blocking mode; in timeout or non-blocking mode file operations that cannot be 748 completed immediately will fail.749 750 Note that the :meth:` connect` operation is subject to the timeout setting, and751 in general it is recommended to call :meth:`settimeout` before calling 752 :meth:`connect` or pass a timeout parameter to :meth:`create_connection`. 753 The system network stack may return a connection timeout error 754 of its own regardless of any Python socket timeout setting.797 returned by the :meth:`~socket.makefile` method must only be used when the 798 socket is in blocking mode; in timeout or non-blocking mode file operations 799 that cannot be completed immediately will fail. 800 801 Note that the :meth:`~socket.connect` operation is subject to the timeout 802 setting, and in general it is recommended to call :meth:`~socket.settimeout` 803 before calling :meth:`~socket.connect` or pass a timeout parameter to 804 :meth:`create_connection`. The system network stack may return a connection 805 timeout error of its own regardless of any Python socket timeout setting. 755 806 756 807 … … 772 823 further receives are disallowed. If *how* is :const:`SHUT_WR`, further sends 773 824 are disallowed. If *how* is :const:`SHUT_RDWR`, further sends and receives are 774 disallowed. 775 776 Note that there are no methods :meth:`read` or :meth:`write`; use :meth:`recv` 777 and :meth:`send` without *flags* argument instead. 825 disallowed. Depending on the platform, shutting down one half of the connection 826 can also close the opposite half (e.g. on Mac OS X, ``shutdown(SHUT_WR)`` does 827 not allow further reads on the other end of the connection). 828 829 Note that there are no methods :meth:`read` or :meth:`write`; use 830 :meth:`~socket.recv` and :meth:`~socket.send` without *flags* argument instead. 778 831 779 832 Socket objects also have these (read-only) attributes that correspond to the … … 809 862 Here are four minimal example programs using the TCP/IP protocol: a server that 810 863 echoes all data that it receives back (servicing only one client), and a client 811 using it. Note that a server must perform the sequence :func:`socket`, 812 :meth:`bind`, :meth:`listen`, :meth:`accept` (possibly repeating the 813 :meth:`accept` to service more than one client), while a client only needs the 814 sequence :func:`socket`, :meth:`connect`. Also note that the server does not 815 :meth:`send`/:meth:`recv` on the socket it is listening on but on the new 816 socket returned by :meth:`accept`. 864 using it. Note that a server must perform the sequence :func:`.socket`, 865 :meth:`~socket.bind`, :meth:`~socket.listen`, :meth:`~socket.accept` (possibly 866 repeating the :meth:`~socket.accept` to service more than one client), while a 867 client only needs the sequence :func:`.socket`, :meth:`~socket.connect`. Also 868 note that the server does not :meth:`~socket.sendall`/:meth:`~socket.recv` on 869 the socket it is listening on but on the new socket returned by 870 :meth:`~socket.accept`. 817 871 818 872 The first two examples support IPv4 only. :: … … 831 885 data = conn.recv(1024) 832 886 if not data: break 833 conn.send (data)887 conn.sendall(data) 834 888 conn.close() 835 889 … … 843 897 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 844 898 s.connect((HOST, PORT)) 845 s.send ('Hello, world')899 s.sendall('Hello, world') 846 900 data = s.recv(1024) 847 901 s.close() … … 867 921 try: 868 922 s = socket.socket(af, socktype, proto) 869 except socket.error ,msg:923 except socket.error as msg: 870 924 s = None 871 925 continue … … 873 927 s.bind(sa) 874 928 s.listen(1) 875 except socket.error ,msg:929 except socket.error as msg: 876 930 s.close() 877 931 s = None … … 902 956 try: 903 957 s = socket.socket(af, socktype, proto) 904 except socket.error ,msg:958 except socket.error as msg: 905 959 s = None 906 960 continue 907 961 try: 908 962 s.connect(sa) 909 except socket.error ,msg:963 except socket.error as msg: 910 964 s.close() 911 965 s = None … … 915 969 print 'could not open socket' 916 970 sys.exit(1) 917 s.send ('Hello, world')971 s.sendall('Hello, world') 918 972 data = s.recv(1024) 919 973 s.close() … … 945 999 # disabled promiscuous mode 946 1000 s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF) 1001 1002 1003 Running an example several times with too small delay between executions, could 1004 lead to this error:: 1005 1006 socket.error: [Errno 98] Address already in use 1007 1008 This is because the previous execution has left the socket in a ``TIME_WAIT`` 1009 state, and can't be immediately reused. 1010 1011 There is a :mod:`socket` flag to set, in order to prevent this, 1012 :data:`socket.SO_REUSEADDR`:: 1013 1014 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 1015 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 1016 s.bind((HOST, PORT)) 1017 1018 the :data:`SO_REUSEADDR` flag tells the kernel to reuse a local socket in 1019 ``TIME_WAIT`` state, without waiting for its natural timeout to expire.
Note:
See TracChangeset
for help on using the changeset viewer.