PageRenderTime 47ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/socket.py

https://bitbucket.org/python_mirrors/releasing-2.7.3
Python | 407 lines | 305 code | 14 blank | 88 comment | 28 complexity | a61841bae40bc2dfc32cf454e1842f39 MD5 | raw file
Possible License(s): BSD-3-Clause, 0BSD
  1. # Wrapper module for _socket, providing some additional facilities
  2. # implemented in Python.
  3. """\
  4. This module provides socket operations and some related functions.
  5. On Unix, it supports IP (Internet Protocol) and Unix domain sockets.
  6. On other systems, it only supports IP. Functions specific for a
  7. socket are available as methods of the socket object.
  8. Functions:
  9. socket() -- create a new socket object
  10. socketpair() -- create a pair of new socket objects [*]
  11. fromfd() -- create a socket object from an open file descriptor [*]
  12. gethostname() -- return the current hostname
  13. gethostbyname() -- map a hostname to its IP number
  14. gethostbyaddr() -- map an IP number or hostname to DNS info
  15. getservbyname() -- map a service name and a protocol name to a port number
  16. getprotobyname() -- map a protocol name (e.g. 'tcp') to a number
  17. ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order
  18. htons(), htonl() -- convert 16, 32 bit int from host to network byte order
  19. inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format
  20. inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89)
  21. socket.getdefaulttimeout() -- get the default timeout value
  22. socket.setdefaulttimeout() -- set the default timeout value
  23. create_connection() -- connects to an address, with an optional timeout and
  24. optional source address.
  25. [*] not available on all platforms!
  26. Special objects:
  27. SocketType -- type object for socket objects
  28. error -- exception raised for I/O errors
  29. has_ipv6 -- boolean value indicating if IPv6 is supported
  30. Integer constants:
  31. AF_INET, AF_UNIX -- socket domains (first argument to socket() call)
  32. SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)
  33. Many other constants may be defined; these may be used in calls to
  34. the setsockopt() and getsockopt() methods.
  35. """
  36. import _socket
  37. from _socket import *
  38. import os, sys, io
  39. try:
  40. import errno
  41. except ImportError:
  42. errno = None
  43. EBADF = getattr(errno, 'EBADF', 9)
  44. EAGAIN = getattr(errno, 'EAGAIN', 11)
  45. EWOULDBLOCK = getattr(errno, 'EWOULDBLOCK', 11)
  46. __all__ = ["getfqdn", "create_connection"]
  47. __all__.extend(os._get_exports_list(_socket))
  48. _realsocket = socket
  49. # WSA error codes
  50. if sys.platform.lower().startswith("win"):
  51. errorTab = {}
  52. errorTab[10004] = "The operation was interrupted."
  53. errorTab[10009] = "A bad file handle was passed."
  54. errorTab[10013] = "Permission denied."
  55. errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT
  56. errorTab[10022] = "An invalid operation was attempted."
  57. errorTab[10035] = "The socket operation would block"
  58. errorTab[10036] = "A blocking operation is already in progress."
  59. errorTab[10048] = "The network address is in use."
  60. errorTab[10054] = "The connection has been reset."
  61. errorTab[10058] = "The network has been shut down."
  62. errorTab[10060] = "The operation timed out."
  63. errorTab[10061] = "Connection refused."
  64. errorTab[10063] = "The name is too long."
  65. errorTab[10064] = "The host is down."
  66. errorTab[10065] = "The host is unreachable."
  67. __all__.append("errorTab")
  68. class socket(_socket.socket):
  69. """A subclass of _socket.socket adding the makefile() method."""
  70. __slots__ = ["__weakref__", "_io_refs", "_closed"]
  71. def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None):
  72. _socket.socket.__init__(self, family, type, proto, fileno)
  73. self._io_refs = 0
  74. self._closed = False
  75. def __enter__(self):
  76. return self
  77. def __exit__(self, *args):
  78. if not self._closed:
  79. self.close()
  80. def __repr__(self):
  81. """Wrap __repr__() to reveal the real class name."""
  82. s = _socket.socket.__repr__(self)
  83. if s.startswith("<socket object"):
  84. s = "<%s.%s%s%s" % (self.__class__.__module__,
  85. self.__class__.__name__,
  86. getattr(self, '_closed', False) and " [closed] " or "",
  87. s[7:])
  88. return s
  89. def __getstate__(self):
  90. raise TypeError("Cannot serialize socket object")
  91. def dup(self):
  92. """dup() -> socket object
  93. Return a new socket object connected to the same system resource.
  94. """
  95. fd = dup(self.fileno())
  96. sock = self.__class__(self.family, self.type, self.proto, fileno=fd)
  97. sock.settimeout(self.gettimeout())
  98. return sock
  99. def accept(self):
  100. """accept() -> (socket object, address info)
  101. Wait for an incoming connection. Return a new socket
  102. representing the connection, and the address of the client.
  103. For IP sockets, the address info is a pair (hostaddr, port).
  104. """
  105. fd, addr = self._accept()
  106. sock = socket(self.family, self.type, self.proto, fileno=fd)
  107. # Issue #7995: if no default timeout is set and the listening
  108. # socket had a (non-zero) timeout, force the new socket in blocking
  109. # mode to override platform-specific socket flags inheritance.
  110. if getdefaulttimeout() is None and self.gettimeout():
  111. sock.setblocking(True)
  112. return sock, addr
  113. def makefile(self, mode="r", buffering=None, *,
  114. encoding=None, errors=None, newline=None):
  115. """makefile(...) -> an I/O stream connected to the socket
  116. The arguments are as for io.open() after the filename,
  117. except the only mode characters supported are 'r', 'w' and 'b'.
  118. The semantics are similar too. (XXX refactor to share code?)
  119. """
  120. for c in mode:
  121. if c not in {"r", "w", "b"}:
  122. raise ValueError("invalid mode %r (only r, w, b allowed)")
  123. writing = "w" in mode
  124. reading = "r" in mode or not writing
  125. assert reading or writing
  126. binary = "b" in mode
  127. rawmode = ""
  128. if reading:
  129. rawmode += "r"
  130. if writing:
  131. rawmode += "w"
  132. raw = SocketIO(self, rawmode)
  133. self._io_refs += 1
  134. if buffering is None:
  135. buffering = -1
  136. if buffering < 0:
  137. buffering = io.DEFAULT_BUFFER_SIZE
  138. if buffering == 0:
  139. if not binary:
  140. raise ValueError("unbuffered streams must be binary")
  141. return raw
  142. if reading and writing:
  143. buffer = io.BufferedRWPair(raw, raw, buffering)
  144. elif reading:
  145. buffer = io.BufferedReader(raw, buffering)
  146. else:
  147. assert writing
  148. buffer = io.BufferedWriter(raw, buffering)
  149. if binary:
  150. return buffer
  151. text = io.TextIOWrapper(buffer, encoding, errors, newline)
  152. text.mode = mode
  153. return text
  154. def _decref_socketios(self):
  155. if self._io_refs > 0:
  156. self._io_refs -= 1
  157. if self._closed:
  158. self.close()
  159. def _real_close(self, _ss=_socket.socket):
  160. # This function should not reference any globals. See issue #808164.
  161. _ss.close(self)
  162. def close(self):
  163. # This function should not reference any globals. See issue #808164.
  164. self._closed = True
  165. if self._io_refs <= 0:
  166. self._real_close()
  167. def fromfd(fd, family, type, proto=0):
  168. """ fromfd(fd, family, type[, proto]) -> socket object
  169. Create a socket object from a duplicate of the given file
  170. descriptor. The remaining arguments are the same as for socket().
  171. """
  172. nfd = dup(fd)
  173. return socket(family, type, proto, nfd)
  174. if hasattr(_socket, "socketpair"):
  175. def socketpair(family=None, type=SOCK_STREAM, proto=0):
  176. """socketpair([family[, type[, proto]]]) -> (socket object, socket object)
  177. Create a pair of socket objects from the sockets returned by the platform
  178. socketpair() function.
  179. The arguments are the same as for socket() except the default family is
  180. AF_UNIX if defined on the platform; otherwise, the default is AF_INET.
  181. """
  182. if family is None:
  183. try:
  184. family = AF_UNIX
  185. except NameError:
  186. family = AF_INET
  187. a, b = _socket.socketpair(family, type, proto)
  188. a = socket(family, type, proto, a.detach())
  189. b = socket(family, type, proto, b.detach())
  190. return a, b
  191. _blocking_errnos = { EAGAIN, EWOULDBLOCK }
  192. class SocketIO(io.RawIOBase):
  193. """Raw I/O implementation for stream sockets.
  194. This class supports the makefile() method on sockets. It provides
  195. the raw I/O interface on top of a socket object.
  196. """
  197. # One might wonder why not let FileIO do the job instead. There are two
  198. # main reasons why FileIO is not adapted:
  199. # - it wouldn't work under Windows (where you can't used read() and
  200. # write() on a socket handle)
  201. # - it wouldn't work with socket timeouts (FileIO would ignore the
  202. # timeout and consider the socket non-blocking)
  203. # XXX More docs
  204. def __init__(self, sock, mode):
  205. if mode not in ("r", "w", "rw", "rb", "wb", "rwb"):
  206. raise ValueError("invalid mode: %r" % mode)
  207. io.RawIOBase.__init__(self)
  208. self._sock = sock
  209. if "b" not in mode:
  210. mode += "b"
  211. self._mode = mode
  212. self._reading = "r" in mode
  213. self._writing = "w" in mode
  214. self._timeout_occurred = False
  215. def readinto(self, b):
  216. """Read up to len(b) bytes into the writable buffer *b* and return
  217. the number of bytes read. If the socket is non-blocking and no bytes
  218. are available, None is returned.
  219. If *b* is non-empty, a 0 return value indicates that the connection
  220. was shutdown at the other end.
  221. """
  222. self._checkClosed()
  223. self._checkReadable()
  224. if self._timeout_occurred:
  225. raise IOError("cannot read from timed out object")
  226. while True:
  227. try:
  228. return self._sock.recv_into(b)
  229. except timeout:
  230. self._timeout_occurred = True
  231. raise
  232. except InterruptedError:
  233. continue
  234. except error as e:
  235. if e.args[0] in _blocking_errnos:
  236. return None
  237. raise
  238. def write(self, b):
  239. """Write the given bytes or bytearray object *b* to the socket
  240. and return the number of bytes written. This can be less than
  241. len(b) if not all data could be written. If the socket is
  242. non-blocking and no bytes could be written None is returned.
  243. """
  244. self._checkClosed()
  245. self._checkWritable()
  246. try:
  247. return self._sock.send(b)
  248. except error as e:
  249. # XXX what about EINTR?
  250. if e.args[0] in _blocking_errnos:
  251. return None
  252. raise
  253. def readable(self):
  254. """True if the SocketIO is open for reading.
  255. """
  256. return self._reading and not self.closed
  257. def writable(self):
  258. """True if the SocketIO is open for writing.
  259. """
  260. return self._writing and not self.closed
  261. def fileno(self):
  262. """Return the file descriptor of the underlying socket.
  263. """
  264. self._checkClosed()
  265. return self._sock.fileno()
  266. @property
  267. def name(self):
  268. if not self.closed:
  269. return self.fileno()
  270. else:
  271. return -1
  272. @property
  273. def mode(self):
  274. return self._mode
  275. def close(self):
  276. """Close the SocketIO object. This doesn't close the underlying
  277. socket, except if all references to it have disappeared.
  278. """
  279. if self.closed:
  280. return
  281. io.RawIOBase.close(self)
  282. self._sock._decref_socketios()
  283. self._sock = None
  284. def getfqdn(name=''):
  285. """Get fully qualified domain name from name.
  286. An empty argument is interpreted as meaning the local host.
  287. First the hostname returned by gethostbyaddr() is checked, then
  288. possibly existing aliases. In case no FQDN is available, hostname
  289. from gethostname() is returned.
  290. """
  291. name = name.strip()
  292. if not name or name == '0.0.0.0':
  293. name = gethostname()
  294. try:
  295. hostname, aliases, ipaddrs = gethostbyaddr(name)
  296. except error:
  297. pass
  298. else:
  299. aliases.insert(0, hostname)
  300. for name in aliases:
  301. if '.' in name:
  302. break
  303. else:
  304. name = hostname
  305. return name
  306. _GLOBAL_DEFAULT_TIMEOUT = object()
  307. def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT,
  308. source_address=None):
  309. """Connect to *address* and return the socket object.
  310. Convenience function. Connect to *address* (a 2-tuple ``(host,
  311. port)``) and return the socket object. Passing the optional
  312. *timeout* parameter will set the timeout on the socket instance
  313. before attempting to connect. If no *timeout* is supplied, the
  314. global default timeout setting returned by :func:`getdefaulttimeout`
  315. is used. If *source_address* is set it must be a tuple of (host, port)
  316. for the socket to bind as a source address before making the connection.
  317. An host of '' or port 0 tells the OS to use the default.
  318. """
  319. host, port = address
  320. err = None
  321. for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  322. af, socktype, proto, canonname, sa = res
  323. sock = None
  324. try:
  325. sock = socket(af, socktype, proto)
  326. if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
  327. sock.settimeout(timeout)
  328. if source_address:
  329. sock.bind(source_address)
  330. sock.connect(sa)
  331. return sock
  332. except error as _:
  333. err = _
  334. if sock is not None:
  335. sock.close()
  336. if err is not None:
  337. raise err
  338. else:
  339. raise error("getaddrinfo returns an empty list")