PageRenderTime 50ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/library/socket.txt

https://bitbucket.org/ymotongpoo/jython25_ja
Plain Text | 910 lines | 694 code | 216 blank | 0 comment | 0 complexity | 1e5f05b6db91e60f13c1e3fe783b740f MD5 | raw file
  1. ``socket`` --- Low-level networking interface
  2. *********************************************
  3. This module provides access to the BSD *socket* interface. It is
  4. available on all modern Unix systems, Windows, Mac OS X, BeOS, OS/2,
  5. and probably additional platforms.
  6. Note: Some behavior may be platform dependent, since calls are made to the
  7. operating system socket APIs.
  8. For an introduction to socket programming (in C), see the following
  9. papers: An Introductory 4.3BSD Interprocess Communication Tutorial, by
  10. Stuart Sechrest and An Advanced 4.3BSD Interprocess Communication
  11. Tutorial, by Samuel J. Leffler et al, both in the UNIX Programmer's
  12. Manual, Supplementary Documents 1 (sections PS1:7 and PS1:8). The
  13. platform-specific reference material for the various socket-related
  14. system calls are also a valuable source of information on the details
  15. of socket semantics. For Unix, refer to the manual pages; for
  16. Windows, see the WinSock (or Winsock 2) specification. For IPv6-ready
  17. APIs, readers may want to refer to **RFC 3493** titled Basic Socket
  18. Interface Extensions for IPv6.
  19. The Python interface is a straightforward transliteration of the Unix
  20. system call and library interface for sockets to Python's object-
  21. oriented style: the ``socket()`` function returns a *socket object*
  22. whose methods implement the various socket system calls. Parameter
  23. types are somewhat higher-level than in the C interface: as with
  24. ``read()`` and ``write()`` operations on Python files, buffer
  25. allocation on receive operations is automatic, and buffer length is
  26. implicit on send operations.
  27. Socket addresses are represented as follows: A single string is used
  28. for the ``AF_UNIX`` address family. A pair ``(host, port)`` is used
  29. for the ``AF_INET`` address family, where *host* is a string
  30. representing either a hostname in Internet domain notation like
  31. ``'daring.cwi.nl'`` or an IPv4 address like ``'100.50.200.5'``, and
  32. *port* is an integral port number. For ``AF_INET6`` address family, a
  33. four-tuple ``(host, port, flowinfo, scopeid)`` is used, where
  34. *flowinfo* and *scopeid* represents ``sin6_flowinfo`` and
  35. ``sin6_scope_id`` member in ``struct sockaddr_in6`` in C. For
  36. ``socket`` module methods, *flowinfo* and *scopeid* can be omitted
  37. just for backward compatibility. Note, however, omission of *scopeid*
  38. can cause problems in manipulating scoped IPv6 addresses. Other
  39. address families are currently not supported. The address format
  40. required by a particular socket object is automatically selected based
  41. on the address family specified when the socket object was created.
  42. For IPv4 addresses, two special forms are accepted instead of a host
  43. address: the empty string represents ``INADDR_ANY``, and the string
  44. ``'<broadcast>'`` represents ``INADDR_BROADCAST``. The behavior is not
  45. available for IPv6 for backward compatibility, therefore, you may want
  46. to avoid these if you intend to support IPv6 with your Python
  47. programs.
  48. If you use a hostname in the *host* portion of IPv4/v6 socket address,
  49. the program may show a nondeterministic behavior, as Python uses the
  50. first address returned from the DNS resolution. The socket address
  51. will be resolved differently into an actual IPv4/v6 address, depending
  52. on the results from DNS resolution and/or the host configuration. For
  53. deterministic behavior use a numeric address in *host* portion.
  54. New in version 2.5: AF_NETLINK sockets are represented as pairs
  55. ``pid, groups``.
  56. New in version 2.6: Linux-only support for TIPC is also available
  57. using the ``AF_TIPC`` address family. TIPC is an open, non-IP based
  58. networked protocol designed for use in clustered computer
  59. environments. Addresses are represented by a tuple, and the fields
  60. depend on the address type. The general tuple form is ``(addr_type,
  61. v1, v2, v3 [, scope])``, where:
  62. * *addr_type* is one of TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, or
  63. TIPC_ADDR_ID.
  64. * *scope* is one of TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and
  65. TIPC_NODE_SCOPE.
  66. * If *addr_type* is TIPC_ADDR_NAME, then *v1* is the server type,
  67. *v2* is the port identifier, and *v3* should be 0.
  68. If *addr_type* is TIPC_ADDR_NAMESEQ, then *v1* is the server
  69. type, *v2* is the lower port number, and *v3* is the upper port
  70. number.
  71. If *addr_type* is TIPC_ADDR_ID, then *v1* is the node, *v2* is
  72. the reference, and *v3* should be set to 0.
  73. All errors raise exceptions. The normal exceptions for invalid
  74. argument types and out-of-memory conditions can be raised; errors
  75. related to socket or address semantics raise the error
  76. ``socket.error``.
  77. Non-blocking mode is supported through ``setblocking()``. A
  78. generalization of this based on timeouts is supported through
  79. ``settimeout()``.
  80. The module ``socket`` exports the following constants and functions:
  81. exception exception socket.error
  82. This exception is raised for socket-related errors. The
  83. accompanying value is either a string telling what went wrong or a
  84. pair ``(errno, string)`` representing an error returned by a system
  85. call, similar to the value accompanying ``os.error``. See the
  86. module ``errno``, which contains names for the error codes defined
  87. by the underlying operating system.
  88. Changed in version 2.6: ``socket.error`` is now a child class of
  89. ``IOError``.
  90. exception exception socket.herror
  91. This exception is raised for address-related errors, i.e. for
  92. functions that use *h_errno* in the C API, including
  93. ``gethostbyname_ex()`` and ``gethostbyaddr()``.
  94. The accompanying value is a pair ``(h_errno, string)`` representing
  95. an error returned by a library call. *string* represents the
  96. description of *h_errno*, as returned by the ``hstrerror()`` C
  97. function.
  98. exception exception socket.gaierror
  99. This exception is raised for address-related errors, for
  100. ``getaddrinfo()`` and ``getnameinfo()``. The accompanying value is
  101. a pair ``(error, string)`` representing an error returned by a
  102. library call. *string* represents the description of *error*, as
  103. returned by the ``gai_strerror()`` C function. The *error* value
  104. will match one of the ``EAI_*`` constants defined in this module.
  105. exception exception socket.timeout
  106. This exception is raised when a timeout occurs on a socket which
  107. has had timeouts enabled via a prior call to ``settimeout()``. The
  108. accompanying value is a string whose value is currently always
  109. "timed out".
  110. New in version 2.3.
  111. socket.AF_UNIX
  112. socket.AF_INET
  113. socket.AF_INET6
  114. These constants represent the address (and protocol) families, used
  115. for the first argument to ``socket()``. If the ``AF_UNIX``
  116. constant is not defined then this protocol is unsupported.
  117. socket.SOCK_STREAM
  118. socket.SOCK_DGRAM
  119. socket.SOCK_RAW
  120. socket.SOCK_RDM
  121. socket.SOCK_SEQPACKET
  122. These constants represent the socket types, used for the second
  123. argument to ``socket()``. (Only ``SOCK_STREAM`` and ``SOCK_DGRAM``
  124. appear to be generally useful.)
  125. SO_*
  126. socket.SOMAXCONN
  127. MSG_*
  128. SOL_*
  129. IPPROTO_*
  130. IPPORT_*
  131. INADDR_*
  132. IP_*
  133. IPV6_*
  134. EAI_*
  135. AI_*
  136. NI_*
  137. TCP_*
  138. Many constants of these forms, documented in the Unix documentation
  139. on sockets and/or the IP protocol, are also defined in the socket
  140. module. They are generally used in arguments to the
  141. ``setsockopt()`` and ``getsockopt()`` methods of socket objects.
  142. In most cases, only those symbols that are defined in the Unix
  143. header files are defined; for a few symbols, default values are
  144. provided.
  145. SIO_*
  146. RCVALL_*
  147. Constants for Windows' WSAIoctl(). The constants are used as
  148. arguments to the ``ioctl()`` method of socket objects.
  149. New in version 2.6.
  150. TIPC_*
  151. TIPC related constants, matching the ones exported by the C socket
  152. API. See the TIPC documentation for more information.
  153. New in version 2.6.
  154. socket.has_ipv6
  155. This constant contains a boolean value which indicates if IPv6 is
  156. supported on this platform.
  157. New in version 2.3.
  158. socket.create_connection(address[, timeout])
  159. Convenience function. Connect to *address* (a 2-tuple ``(host,
  160. port)``), and return the socket object. Passing the optional
  161. *timeout* parameter will set the timeout on the socket instance
  162. before attempting to connect. If no *timeout* is supplied, the
  163. global default timeout setting returned by ``getdefaulttimeout()``
  164. is used.
  165. New in version 2.6.
  166. socket.getaddrinfo(host, port[, family[, socktype[, proto[, flags]]]])
  167. Resolves the *host*/*port* argument, into a sequence of 5-tuples
  168. that contain all the necessary arguments for creating the
  169. corresponding socket. *host* is a domain name, a string
  170. representation of an IPv4/v6 address or ``None``. *port* is a
  171. string service name such as ``'http'``, a numeric port number or
  172. ``None``. The rest of the arguments are optional and must be
  173. numeric if specified. By passing ``None`` as the value of *host*
  174. and *port*, , you can pass ``NULL`` to the C API.
  175. The ``getaddrinfo()`` function returns a list of 5-tuples with the
  176. following structure:
  177. ``(family, socktype, proto, canonname, sockaddr)``
  178. *family*, *socktype*, *proto* are all integers and are meant to be
  179. passed to the ``socket()`` function. *canonname* is a string
  180. representing the canonical name of the *host*. It can be a numeric
  181. IPv4/v6 address when ``AI_CANONNAME`` is specified for a numeric
  182. *host*. *sockaddr* is a tuple describing a socket address, as
  183. described above. See the source for ``socket`` and other library
  184. modules for a typical usage of the function.
  185. New in version 2.2.
  186. socket.getfqdn([name])
  187. Return a fully qualified domain name for *name*. If *name* is
  188. omitted or empty, it is interpreted as the local host. To find the
  189. fully qualified name, the hostname returned by ``gethostbyaddr()``
  190. is checked, followed by aliases for the host, if available. The
  191. first name which includes a period is selected. In case no fully
  192. qualified domain name is available, the hostname as returned by
  193. ``gethostname()`` is returned.
  194. New in version 2.0.
  195. socket.gethostbyname(hostname)
  196. Translate a host name to IPv4 address format. The IPv4 address is
  197. returned as a string, such as ``'100.50.200.5'``. If the host
  198. name is an IPv4 address itself it is returned unchanged. See
  199. ``gethostbyname_ex()`` for a more complete interface.
  200. ``gethostbyname()`` does not support IPv6 name resolution, and
  201. ``getaddrinfo()`` should be used instead for IPv4/v6 dual stack
  202. support.
  203. socket.gethostbyname_ex(hostname)
  204. Translate a host name to IPv4 address format, extended interface.
  205. Return a triple ``(hostname, aliaslist, ipaddrlist)`` where
  206. *hostname* is the primary host name responding to the given
  207. *ip_address*, *aliaslist* is a (possibly empty) list of alternative
  208. host names for the same address, and *ipaddrlist* is a list of IPv4
  209. addresses for the same interface on the same host (often but not
  210. always a single address). ``gethostbyname_ex()`` does not support
  211. IPv6 name resolution, and ``getaddrinfo()`` should be used instead
  212. for IPv4/v6 dual stack support.
  213. socket.gethostname()
  214. Return a string containing the hostname of the machine where the
  215. Python interpreter is currently executing.
  216. If you want to know the current machine's IP address, you may want
  217. to use ``gethostbyname(gethostname())``. This operation assumes
  218. that there is a valid address-to-host mapping for the host, and the
  219. assumption does not always hold.
  220. Note: ``gethostname()`` doesn't always return the fully qualified
  221. domain name; use ``getfqdn()`` (see above).
  222. socket.gethostbyaddr(ip_address)
  223. Return a triple ``(hostname, aliaslist, ipaddrlist)`` where
  224. *hostname* is the primary host name responding to the given
  225. *ip_address*, *aliaslist* is a (possibly empty) list of alternative
  226. host names for the same address, and *ipaddrlist* is a list of
  227. IPv4/v6 addresses for the same interface on the same host (most
  228. likely containing only a single address). To find the fully
  229. qualified domain name, use the function ``getfqdn()``.
  230. ``gethostbyaddr()`` supports both IPv4 and IPv6.
  231. socket.getnameinfo(sockaddr, flags)
  232. Translate a socket address *sockaddr* into a 2-tuple ``(host,
  233. port)``. Depending on the settings of *flags*, the result can
  234. contain a fully-qualified domain name or numeric address
  235. representation in *host*. Similarly, *port* can contain a string
  236. port name or a numeric port number.
  237. New in version 2.2.
  238. socket.getprotobyname(protocolname)
  239. Translate an Internet protocol name (for example, ``'icmp'``) to a
  240. constant suitable for passing as the (optional) third argument to
  241. the ``socket()`` function. This is usually only needed for sockets
  242. opened in "raw" mode (``SOCK_RAW``); for the normal socket modes,
  243. the correct protocol is chosen automatically if the protocol is
  244. omitted or zero.
  245. socket.getservbyname(servicename[, protocolname])
  246. Translate an Internet service name and protocol name to a port
  247. number for that service. The optional protocol name, if given,
  248. should be ``'tcp'`` or ``'udp'``, otherwise any protocol will
  249. match.
  250. socket.getservbyport(port[, protocolname])
  251. Translate an Internet port number and protocol name to a service
  252. name for that service. The optional protocol name, if given,
  253. should be ``'tcp'`` or ``'udp'``, otherwise any protocol will
  254. match.
  255. socket.socket([family[, type[, proto]]])
  256. Create a new socket using the given address family, socket type and
  257. protocol number. The address family should be ``AF_INET`` (the
  258. default), ``AF_INET6`` or ``AF_UNIX``. The socket type should be
  259. ``SOCK_STREAM`` (the default), ``SOCK_DGRAM`` or perhaps one of the
  260. other ``SOCK_`` constants. The protocol number is usually zero and
  261. may be omitted in that case.
  262. socket.socketpair([family[, type[, proto]]])
  263. Build a pair of connected socket objects using the given address
  264. family, socket type, and protocol number. Address family, socket
  265. type, and protocol number are as for the ``socket()`` function
  266. above. The default family is ``AF_UNIX`` if defined on the
  267. platform; otherwise, the default is ``AF_INET``. Availability:
  268. Unix.
  269. New in version 2.4.
  270. socket.fromfd(fd, family, type[, proto])
  271. Duplicate the file descriptor *fd* (an integer as returned by a
  272. file object's ``fileno()`` method) and build a socket object from
  273. the result. Address family, socket type and protocol number are as
  274. for the ``socket()`` function above. The file descriptor should
  275. refer to a socket, but this is not checked --- subsequent
  276. operations on the object may fail if the file descriptor is
  277. invalid. This function is rarely needed, but can be used to get or
  278. set socket options on a socket passed to a program as standard
  279. input or output (such as a server started by the Unix inet daemon).
  280. The socket is assumed to be in blocking mode. Availability: Unix.
  281. socket.ntohl(x)
  282. Convert 32-bit positive integers from network to host byte order.
  283. On machines where the host byte order is the same as network byte
  284. order, this is a no-op; otherwise, it performs a 4-byte swap
  285. operation.
  286. socket.ntohs(x)
  287. Convert 16-bit positive integers from network to host byte order.
  288. On machines where the host byte order is the same as network byte
  289. order, this is a no-op; otherwise, it performs a 2-byte swap
  290. operation.
  291. socket.htonl(x)
  292. Convert 32-bit positive integers from host to network byte order.
  293. On machines where the host byte order is the same as network byte
  294. order, this is a no-op; otherwise, it performs a 4-byte swap
  295. operation.
  296. socket.htons(x)
  297. Convert 16-bit positive integers from host to network byte order.
  298. On machines where the host byte order is the same as network byte
  299. order, this is a no-op; otherwise, it performs a 2-byte swap
  300. operation.
  301. socket.inet_aton(ip_string)
  302. Convert an IPv4 address from dotted-quad string format (for
  303. example, '123.45.67.89') to 32-bit packed binary format, as a
  304. string four characters in length. This is useful when conversing
  305. with a program that uses the standard C library and needs objects
  306. of type ``struct in_addr``, which is the C type for the 32-bit
  307. packed binary this function returns.
  308. If the IPv4 address string passed to this function is invalid,
  309. ``socket.error`` will be raised. Note that exactly what is valid
  310. depends on the underlying C implementation of ``inet_aton()``.
  311. ``inet_aton()`` does not support IPv6, and ``inet_pton()`` should
  312. be used instead for IPv4/v6 dual stack support.
  313. socket.inet_ntoa(packed_ip)
  314. Convert a 32-bit packed IPv4 address (a string four characters in
  315. length) to its standard dotted-quad string representation (for
  316. example, '123.45.67.89'). This is useful when conversing with a
  317. program that uses the standard C library and needs objects of type
  318. ``struct in_addr``, which is the C type for the 32-bit packed
  319. binary data this function takes as an argument.
  320. If the string passed to this function is not exactly 4 bytes in
  321. length, ``socket.error`` will be raised. ``inet_ntoa()`` does not
  322. support IPv6, and ``inet_ntop()`` should be used instead for
  323. IPv4/v6 dual stack support.
  324. socket.inet_pton(address_family, ip_string)
  325. Convert an IP address from its family-specific string format to a
  326. packed, binary format. ``inet_pton()`` is useful when a library or
  327. network protocol calls for an object of type ``struct in_addr``
  328. (similar to ``inet_aton()``) or ``struct in6_addr``.
  329. Supported values for *address_family* are currently ``AF_INET`` and
  330. ``AF_INET6``. If the IP address string *ip_string* is invalid,
  331. ``socket.error`` will be raised. Note that exactly what is valid
  332. depends on both the value of *address_family* and the underlying
  333. implementation of ``inet_pton()``.
  334. Availability: Unix (maybe not all platforms).
  335. See also:
  336. ``ipaddr.BaseIP.packed()``
  337. Platform-independent conversion to a packed, binary format.
  338. New in version 2.3.
  339. socket.inet_ntop(address_family, packed_ip)
  340. Convert a packed IP address (a string of some number of characters)
  341. to its standard, family-specific string representation (for
  342. example, ``'7.10.0.5'`` or ``'5aef:2b::8'``) ``inet_ntop()`` is
  343. useful when a library or network protocol returns an object of type
  344. ``struct in_addr`` (similar to ``inet_ntoa()``) or ``struct
  345. in6_addr``.
  346. Supported values for *address_family* are currently ``AF_INET`` and
  347. ``AF_INET6``. If the string *packed_ip* is not the correct length
  348. for the specified address family, ``ValueError`` will be raised. A
  349. ``socket.error`` is raised for errors from the call to
  350. ``inet_ntop()``.
  351. Availability: Unix (maybe not all platforms).
  352. New in version 2.3.
  353. socket.getdefaulttimeout()
  354. Return the default timeout in floating seconds for new socket
  355. objects. A value of ``None`` indicates that new socket objects have
  356. no timeout. When the socket module is first imported, the default
  357. is ``None``.
  358. New in version 2.3.
  359. socket.setdefaulttimeout(timeout)
  360. Set the default timeout in floating seconds for new socket objects.
  361. A value of ``None`` indicates that new socket objects have no
  362. timeout. When the socket module is first imported, the default is
  363. ``None``.
  364. New in version 2.3.
  365. socket.SocketType
  366. This is a Python type object that represents the socket object
  367. type. It is the same as ``type(socket(...))``.
  368. See also:
  369. Module ``SocketServer``
  370. Classes that simplify writing network servers.
  371. Socket Objects
  372. ==============
  373. Socket objects have the following methods. Except for ``makefile()``
  374. these correspond to Unix system calls applicable to sockets.
  375. socket.accept()
  376. Accept a connection. The socket must be bound to an address and
  377. listening for connections. The return value is a pair ``(conn,
  378. address)`` where *conn* is a *new* socket object usable to send and
  379. receive data on the connection, and *address* is the address bound
  380. to the socket on the other end of the connection.
  381. socket.bind(address)
  382. Bind the socket to *address*. The socket must not already be
  383. bound. (The format of *address* depends on the address family ---
  384. see above.)
  385. Note: This method has historically accepted a pair of parameters for
  386. ``AF_INET`` addresses instead of only a tuple. This was never
  387. intentional and is no longer available in Python 2.0 and later.
  388. socket.close()
  389. Close the socket. All future operations on the socket object will
  390. fail. The remote end will receive no more data (after queued data
  391. is flushed). Sockets are automatically closed when they are
  392. garbage-collected.
  393. socket.connect(address)
  394. Connect to a remote socket at *address*. (The format of *address*
  395. depends on the address family --- see above.)
  396. Note: This method has historically accepted a pair of parameters for
  397. ``AF_INET`` addresses instead of only a tuple. This was never
  398. intentional and is no longer available in Python 2.0 and later.
  399. socket.connect_ex(address)
  400. Like ``connect(address)``, but return an error indicator instead of
  401. raising an exception for errors returned by the C-level
  402. ``connect()`` call (other problems, such as "host not found," can
  403. still raise exceptions). The error indicator is ``0`` if the
  404. operation succeeded, otherwise the value of the ``errno`` variable.
  405. This is useful to support, for example, asynchronous connects.
  406. Note: This method has historically accepted a pair of parameters for
  407. ``AF_INET`` addresses instead of only a tuple. This was never
  408. intentional and is no longer available in Python 2.0 and later.
  409. socket.fileno()
  410. Return the socket's file descriptor (a small integer). This is
  411. useful with ``select.select()``.
  412. Under Windows the small integer returned by this method cannot be
  413. used where a file descriptor can be used (such as ``os.fdopen()``).
  414. Unix does not have this limitation.
  415. socket.getpeername()
  416. Return the remote address to which the socket is connected. This
  417. is useful to find out the port number of a remote IPv4/v6 socket,
  418. for instance. (The format of the address returned depends on the
  419. address family --- see above.) On some systems this function is
  420. not supported.
  421. socket.getsockname()
  422. Return the socket's own address. This is useful to find out the
  423. port number of an IPv4/v6 socket, for instance. (The format of the
  424. address returned depends on the address family --- see above.)
  425. socket.getsockopt(level, optname[, buflen])
  426. Return the value of the given socket option (see the Unix man page
  427. *getsockopt(2)*). The needed symbolic constants (``SO_*`` etc.)
  428. are defined in this module. If *buflen* is absent, an integer
  429. option is assumed and its integer value is returned by the
  430. function. If *buflen* is present, it specifies the maximum length
  431. of the buffer used to receive the option in, and this buffer is
  432. returned as a string. It is up to the caller to decode the
  433. contents of the buffer (see the optional built-in module ``struct``
  434. for a way to decode C structures encoded as strings).
  435. socket.ioctl(control, option)
  436. Platform:
  437. Windows
  438. The ``ioctl()`` method is a limited interface to the WSAIoctl
  439. system interface. Please refer to the MSDN documentation for more
  440. information.
  441. New in version 2.6.
  442. socket.listen(backlog)
  443. Listen for connections made to the socket. The *backlog* argument
  444. specifies the maximum number of queued connections and should be at
  445. least 1; the maximum value is system-dependent (usually 5).
  446. socket.makefile([mode[, bufsize]])
  447. Return a *file object* associated with the socket. (File objects
  448. are described in *File Objects*.) The file object references a
  449. ``dup()``ped version of the socket file descriptor, so the file
  450. object and socket object may be closed or garbage-collected
  451. independently. The socket must be in blocking mode (it can not have
  452. a timeout). The optional *mode* and *bufsize* arguments are
  453. interpreted the same way as by the built-in ``file()`` function.
  454. socket.recv(bufsize[, flags])
  455. Receive data from the socket. The return value is a string
  456. representing the data received. The maximum amount of data to be
  457. received at once is specified by *bufsize*. See the Unix manual
  458. page *recv(2)* for the meaning of the optional argument *flags*; it
  459. defaults to zero.
  460. Note: For best match with hardware and network realities, the value of
  461. *bufsize* should be a relatively small power of 2, for example,
  462. 4096.
  463. socket.recvfrom(bufsize[, flags])
  464. Receive data from the socket. The return value is a pair
  465. ``(string, address)`` where *string* is a string representing the
  466. data received and *address* is the address of the socket sending
  467. the data. See the Unix manual page *recv(2)* for the meaning of
  468. the optional argument *flags*; it defaults to zero. (The format of
  469. *address* depends on the address family --- see above.)
  470. socket.recvfrom_into(buffer[, nbytes[, flags]])
  471. Receive data from the socket, writing it into *buffer* instead of
  472. creating a new string. The return value is a pair ``(nbytes,
  473. address)`` where *nbytes* is the number of bytes received and
  474. *address* is the address of the socket sending the data. See the
  475. Unix manual page *recv(2)* for the meaning of the optional argument
  476. *flags*; it defaults to zero. (The format of *address* depends on
  477. the address family --- see above.)
  478. New in version 2.5.
  479. socket.recv_into(buffer[, nbytes[, flags]])
  480. Receive up to *nbytes* bytes from the socket, storing the data into
  481. a buffer rather than creating a new string. If *nbytes* is not
  482. specified (or 0), receive up to the size available in the given
  483. buffer. See the Unix manual page *recv(2)* for the meaning of the
  484. optional argument *flags*; it defaults to zero.
  485. New in version 2.5.
  486. socket.send(string[, flags])
  487. Send data to the socket. The socket must be connected to a remote
  488. socket. The optional *flags* argument has the same meaning as for
  489. ``recv()`` above. Returns the number of bytes sent. Applications
  490. are responsible for checking that all data has been sent; if only
  491. some of the data was transmitted, the application needs to attempt
  492. delivery of the remaining data.
  493. socket.sendall(string[, flags])
  494. Send data to the socket. The socket must be connected to a remote
  495. socket. The optional *flags* argument has the same meaning as for
  496. ``recv()`` above. Unlike ``send()``, this method continues to send
  497. data from *string* until either all data has been sent or an error
  498. occurs. ``None`` is returned on success. On error, an exception
  499. is raised, and there is no way to determine how much data, if any,
  500. was successfully sent.
  501. socket.sendto(string[, flags], address)
  502. Send data to the socket. The socket should not be connected to a
  503. remote socket, since the destination socket is specified by
  504. *address*. The optional *flags* argument has the same meaning as
  505. for ``recv()`` above. Return the number of bytes sent. (The format
  506. of *address* depends on the address family --- see above.)
  507. socket.setblocking(flag)
  508. Set blocking or non-blocking mode of the socket: if *flag* is 0,
  509. the socket is set to non-blocking, else to blocking mode.
  510. Initially all sockets are in blocking mode. In non-blocking mode,
  511. if a ``recv()`` call doesn't find any data, or if a ``send()`` call
  512. can't immediately dispose of the data, a ``error`` exception is
  513. raised; in blocking mode, the calls block until they can proceed.
  514. ``s.setblocking(0)`` is equivalent to ``s.settimeout(0)``;
  515. ``s.setblocking(1)`` is equivalent to ``s.settimeout(None)``.
  516. socket.settimeout(value)
  517. Set a timeout on blocking socket operations. The *value* argument
  518. can be a nonnegative float expressing seconds, or ``None``. If a
  519. float is given, subsequent socket operations will raise an
  520. ``timeout`` exception if the timeout period *value* has elapsed
  521. before the operation has completed. Setting a timeout of ``None``
  522. disables timeouts on socket operations. ``s.settimeout(0.0)`` is
  523. equivalent to ``s.setblocking(0)``; ``s.settimeout(None)`` is
  524. equivalent to ``s.setblocking(1)``.
  525. New in version 2.3.
  526. socket.gettimeout()
  527. Return the timeout in floating seconds associated with socket
  528. operations, or ``None`` if no timeout is set. This reflects the
  529. last call to ``setblocking()`` or ``settimeout()``.
  530. New in version 2.3.
  531. Some notes on socket blocking and timeouts: A socket object can be in
  532. one of three modes: blocking, non-blocking, or timeout. Sockets are
  533. always created in blocking mode. In blocking mode, operations block
  534. until complete. In non-blocking mode, operations fail (with an error
  535. that is unfortunately system-dependent) if they cannot be completed
  536. immediately. In timeout mode, operations fail if they cannot be
  537. completed within the timeout specified for the socket. The
  538. ``setblocking()`` method is simply a shorthand for certain
  539. ``settimeout()`` calls.
  540. Timeout mode internally sets the socket in non-blocking mode. The
  541. blocking and timeout modes are shared between file descriptors and
  542. socket objects that refer to the same network endpoint. A consequence
  543. of this is that file objects returned by the ``makefile()`` method
  544. must only be used when the socket is in blocking mode; in timeout or
  545. non-blocking mode file operations that cannot be completed immediately
  546. will fail.
  547. Note that the ``connect()`` operation is subject to the timeout
  548. setting, and in general it is recommended to call ``settimeout()``
  549. before calling ``connect()``.
  550. socket.setsockopt(level, optname, value)
  551. Set the value of the given socket option (see the Unix manual page
  552. *setsockopt(2)*). The needed symbolic constants are defined in the
  553. ``socket`` module (``SO_*`` etc.). The value can be an integer or
  554. a string representing a buffer. In the latter case it is up to the
  555. caller to ensure that the string contains the proper bits (see the
  556. optional built-in module ``struct`` for a way to encode C
  557. structures as strings).
  558. socket.shutdown(how)
  559. Shut down one or both halves of the connection. If *how* is
  560. ``SHUT_RD``, further receives are disallowed. If *how* is
  561. ``SHUT_WR``, further sends are disallowed. If *how* is
  562. ``SHUT_RDWR``, further sends and receives are disallowed.
  563. Note that there are no methods ``read()`` or ``write()``; use
  564. ``recv()`` and ``send()`` without *flags* argument instead.
  565. Socket objects also have these (read-only) attributes that correspond
  566. to the values given to the ``socket`` constructor.
  567. socket.family
  568. The socket family.
  569. New in version 2.5.
  570. socket.type
  571. The socket type.
  572. New in version 2.5.
  573. socket.proto
  574. The socket protocol.
  575. New in version 2.5.
  576. Example
  577. =======
  578. Here are four minimal example programs using the TCP/IP protocol: a
  579. server that echoes all data that it receives back (servicing only one
  580. client), and a client using it. Note that a server must perform the
  581. sequence ``socket()``, ``bind()``, ``listen()``, ``accept()``
  582. (possibly repeating the ``accept()`` to service more than one client),
  583. while a client only needs the sequence ``socket()``, ``connect()``.
  584. Also note that the server does not ``send()``/``recv()`` on the
  585. socket it is listening on but on the new socket returned by
  586. ``accept()``.
  587. The first two examples support IPv4 only.
  588. # Echo server program
  589. import socket
  590. HOST = '' # Symbolic name meaning all available interfaces
  591. PORT = 50007 # Arbitrary non-privileged port
  592. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  593. s.bind((HOST, PORT))
  594. s.listen(1)
  595. conn, addr = s.accept()
  596. print 'Connected by', addr
  597. while 1:
  598. data = conn.recv(1024)
  599. if not data: break
  600. conn.send(data)
  601. conn.close()
  602. # Echo client program
  603. import socket
  604. HOST = 'daring.cwi.nl' # The remote host
  605. PORT = 50007 # The same port as used by the server
  606. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  607. s.connect((HOST, PORT))
  608. s.send('Hello, world')
  609. data = s.recv(1024)
  610. s.close()
  611. print 'Received', repr(data)
  612. The next two examples are identical to the above two, but support both
  613. IPv4 and IPv6. The server side will listen to the first address family
  614. available (it should listen to both instead). On most of IPv6-ready
  615. systems, IPv6 will take precedence and the server may not accept IPv4
  616. traffic. The client side will try to connect to the all addresses
  617. returned as a result of the name resolution, and sends traffic to the
  618. first one connected successfully.
  619. # Echo server program
  620. import socket
  621. import sys
  622. HOST = None # Symbolic name meaning all available interfaces
  623. PORT = 50007 # Arbitrary non-privileged port
  624. s = None
  625. for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,
  626. socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
  627. af, socktype, proto, canonname, sa = res
  628. try:
  629. s = socket.socket(af, socktype, proto)
  630. except socket.error, msg:
  631. s = None
  632. continue
  633. try:
  634. s.bind(sa)
  635. s.listen(1)
  636. except socket.error, msg:
  637. s.close()
  638. s = None
  639. continue
  640. break
  641. if s is None:
  642. print 'could not open socket'
  643. sys.exit(1)
  644. conn, addr = s.accept()
  645. print 'Connected by', addr
  646. while 1:
  647. data = conn.recv(1024)
  648. if not data: break
  649. conn.send(data)
  650. conn.close()
  651. # Echo client program
  652. import socket
  653. import sys
  654. HOST = 'daring.cwi.nl' # The remote host
  655. PORT = 50007 # The same port as used by the server
  656. s = None
  657. for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
  658. af, socktype, proto, canonname, sa = res
  659. try:
  660. s = socket.socket(af, socktype, proto)
  661. except socket.error, msg:
  662. s = None
  663. continue
  664. try:
  665. s.connect(sa)
  666. except socket.error, msg:
  667. s.close()
  668. s = None
  669. continue
  670. break
  671. if s is None:
  672. print 'could not open socket'
  673. sys.exit(1)
  674. s.send('Hello, world')
  675. data = s.recv(1024)
  676. s.close()
  677. print 'Received', repr(data)
  678. The last example shows how to write a very simple network sniffer with
  679. raw sockets on Windows. The example requires administrator privileges
  680. to modify the interface:
  681. import socket
  682. # the public network interface
  683. HOST = socket.gethostbyname(socket.gethostname())
  684. # create a raw socket and bind it to the public interface
  685. s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
  686. s.bind((HOST, 0))
  687. # Include IP headers
  688. s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
  689. # receive all packages
  690. s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
  691. # receive a package
  692. print s.recvfrom(65565)
  693. # disabled promiscuous mode
  694. s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)