socket.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  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. fromshare() -- create a socket object from data received from socket.share() [*]
  13. gethostname() -- return the current hostname
  14. gethostbyname() -- map a hostname to its IP number
  15. gethostbyaddr() -- map an IP number or hostname to DNS info
  16. getservbyname() -- map a service name and a protocol name to a port number
  17. getprotobyname() -- map a protocol name (e.g. 'tcp') to a number
  18. ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order
  19. htons(), htonl() -- convert 16, 32 bit int from host to network byte order
  20. inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format
  21. inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89)
  22. socket.getdefaulttimeout() -- get the default timeout value
  23. socket.setdefaulttimeout() -- set the default timeout value
  24. create_connection() -- connects to an address, with an optional timeout and
  25. optional source address.
  26. [*] not available on all platforms!
  27. Special objects:
  28. SocketType -- type object for socket objects
  29. error -- exception raised for I/O errors
  30. has_ipv6 -- boolean value indicating if IPv6 is supported
  31. IntEnum constants:
  32. AF_INET, AF_UNIX -- socket domains (first argument to socket() call)
  33. SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)
  34. Integer constants:
  35. Many other constants may be defined; these may be used in calls to
  36. the setsockopt() and getsockopt() methods.
  37. """
  38. import _socket
  39. from _socket import *
  40. import os, sys, io, selectors
  41. from enum import IntEnum, IntFlag
  42. try:
  43. import errno
  44. except ImportError:
  45. errno = None
  46. EBADF = getattr(errno, 'EBADF', 9)
  47. EAGAIN = getattr(errno, 'EAGAIN', 11)
  48. EWOULDBLOCK = getattr(errno, 'EWOULDBLOCK', 11)
  49. __all__ = ["fromfd", "getfqdn", "create_connection",
  50. "AddressFamily", "SocketKind"]
  51. __all__.extend(os._get_exports_list(_socket))
  52. # Set up the socket.AF_* socket.SOCK_* constants as members of IntEnums for
  53. # nicer string representations.
  54. # Note that _socket only knows about the integer values. The public interface
  55. # in this module understands the enums and translates them back from integers
  56. # where needed (e.g. .family property of a socket object).
  57. IntEnum._convert(
  58. 'AddressFamily',
  59. __name__,
  60. lambda C: C.isupper() and C.startswith('AF_'))
  61. IntEnum._convert(
  62. 'SocketKind',
  63. __name__,
  64. lambda C: C.isupper() and C.startswith('SOCK_'))
  65. IntFlag._convert(
  66. 'MsgFlag',
  67. __name__,
  68. lambda C: C.isupper() and C.startswith('MSG_'))
  69. IntFlag._convert(
  70. 'AddressInfo',
  71. __name__,
  72. lambda C: C.isupper() and C.startswith('AI_'))
  73. _LOCALHOST = '127.0.0.1'
  74. _LOCALHOST_V6 = '::1'
  75. def _intenum_converter(value, enum_klass):
  76. """Convert a numeric family value to an IntEnum member.
  77. If it's not a known member, return the numeric value itself.
  78. """
  79. try:
  80. return enum_klass(value)
  81. except ValueError:
  82. return value
  83. _realsocket = socket
  84. # WSA error codes
  85. if sys.platform.lower().startswith("win"):
  86. errorTab = {}
  87. errorTab[10004] = "The operation was interrupted."
  88. errorTab[10009] = "A bad file handle was passed."
  89. errorTab[10013] = "Permission denied."
  90. errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT
  91. errorTab[10022] = "An invalid operation was attempted."
  92. errorTab[10035] = "The socket operation would block"
  93. errorTab[10036] = "A blocking operation is already in progress."
  94. errorTab[10048] = "The network address is in use."
  95. errorTab[10054] = "The connection has been reset."
  96. errorTab[10058] = "The network has been shut down."
  97. errorTab[10060] = "The operation timed out."
  98. errorTab[10061] = "Connection refused."
  99. errorTab[10063] = "The name is too long."
  100. errorTab[10064] = "The host is down."
  101. errorTab[10065] = "The host is unreachable."
  102. __all__.append("errorTab")
  103. class _GiveupOnSendfile(Exception): pass
  104. class socket(_socket.socket):
  105. """A subclass of _socket.socket adding the makefile() method."""
  106. __slots__ = ["__weakref__", "_io_refs", "_closed"]
  107. def __init__(self, family=-1, type=-1, proto=-1, fileno=None):
  108. # For user code address family and type values are IntEnum members, but
  109. # for the underlying _socket.socket they're just integers. The
  110. # constructor of _socket.socket converts the given argument to an
  111. # integer automatically.
  112. if fileno is None:
  113. if family == -1:
  114. family = AF_INET
  115. if type == -1:
  116. type = SOCK_STREAM
  117. if proto == -1:
  118. proto = 0
  119. _socket.socket.__init__(self, family, type, proto, fileno)
  120. self._io_refs = 0
  121. self._closed = False
  122. def __enter__(self):
  123. return self
  124. def __exit__(self, *args):
  125. if not self._closed:
  126. self.close()
  127. def __repr__(self):
  128. """Wrap __repr__() to reveal the real class name and socket
  129. address(es).
  130. """
  131. closed = getattr(self, '_closed', False)
  132. s = "<%s.%s%s fd=%i, family=%s, type=%s, proto=%i" \
  133. % (self.__class__.__module__,
  134. self.__class__.__qualname__,
  135. " [closed]" if closed else "",
  136. self.fileno(),
  137. self.family,
  138. self.type,
  139. self.proto)
  140. if not closed:
  141. try:
  142. laddr = self.getsockname()
  143. if laddr:
  144. s += ", laddr=%s" % str(laddr)
  145. except error:
  146. pass
  147. try:
  148. raddr = self.getpeername()
  149. if raddr:
  150. s += ", raddr=%s" % str(raddr)
  151. except error:
  152. pass
  153. s += '>'
  154. return s
  155. def __getstate__(self):
  156. raise TypeError("Cannot serialize socket object")
  157. def dup(self):
  158. """dup() -> socket object
  159. Duplicate the socket. Return a new socket object connected to the same
  160. system resource. The new socket is non-inheritable.
  161. """
  162. fd = dup(self.fileno())
  163. sock = self.__class__(self.family, self.type, self.proto, fileno=fd)
  164. sock.settimeout(self.gettimeout())
  165. return sock
  166. def accept(self):
  167. """accept() -> (socket object, address info)
  168. Wait for an incoming connection. Return a new socket
  169. representing the connection, and the address of the client.
  170. For IP sockets, the address info is a pair (hostaddr, port).
  171. """
  172. fd, addr = self._accept()
  173. sock = socket(self.family, self.type, self.proto, fileno=fd)
  174. # Issue #7995: if no default timeout is set and the listening
  175. # socket had a (non-zero) timeout, force the new socket in blocking
  176. # mode to override platform-specific socket flags inheritance.
  177. if getdefaulttimeout() is None and self.gettimeout():
  178. sock.setblocking(True)
  179. return sock, addr
  180. def makefile(self, mode="r", buffering=None, *,
  181. encoding=None, errors=None, newline=None):
  182. """makefile(...) -> an I/O stream connected to the socket
  183. The arguments are as for io.open() after the filename, except the only
  184. supported mode values are 'r' (default), 'w' and 'b'.
  185. """
  186. # XXX refactor to share code?
  187. if not set(mode) <= {"r", "w", "b"}:
  188. raise ValueError("invalid mode %r (only r, w, b allowed)" % (mode,))
  189. writing = "w" in mode
  190. reading = "r" in mode or not writing
  191. assert reading or writing
  192. binary = "b" in mode
  193. rawmode = ""
  194. if reading:
  195. rawmode += "r"
  196. if writing:
  197. rawmode += "w"
  198. raw = SocketIO(self, rawmode)
  199. self._io_refs += 1
  200. if buffering is None:
  201. buffering = -1
  202. if buffering < 0:
  203. buffering = io.DEFAULT_BUFFER_SIZE
  204. if buffering == 0:
  205. if not binary:
  206. raise ValueError("unbuffered streams must be binary")
  207. return raw
  208. if reading and writing:
  209. buffer = io.BufferedRWPair(raw, raw, buffering)
  210. elif reading:
  211. buffer = io.BufferedReader(raw, buffering)
  212. else:
  213. assert writing
  214. buffer = io.BufferedWriter(raw, buffering)
  215. if binary:
  216. return buffer
  217. text = io.TextIOWrapper(buffer, encoding, errors, newline)
  218. text.mode = mode
  219. return text
  220. if hasattr(os, 'sendfile'):
  221. def _sendfile_use_sendfile(self, file, offset=0, count=None):
  222. self._check_sendfile_params(file, offset, count)
  223. sockno = self.fileno()
  224. try:
  225. fileno = file.fileno()
  226. except (AttributeError, io.UnsupportedOperation) as err:
  227. raise _GiveupOnSendfile(err) # not a regular file
  228. try:
  229. fsize = os.fstat(fileno).st_size
  230. except OSError as err:
  231. raise _GiveupOnSendfile(err) # not a regular file
  232. if not fsize:
  233. return 0 # empty file
  234. blocksize = fsize if not count else count
  235. timeout = self.gettimeout()
  236. if timeout == 0:
  237. raise ValueError("non-blocking sockets are not supported")
  238. # poll/select have the advantage of not requiring any
  239. # extra file descriptor, contrarily to epoll/kqueue
  240. # (also, they require a single syscall).
  241. if hasattr(selectors, 'PollSelector'):
  242. selector = selectors.PollSelector()
  243. else:
  244. selector = selectors.SelectSelector()
  245. selector.register(sockno, selectors.EVENT_WRITE)
  246. total_sent = 0
  247. # localize variable access to minimize overhead
  248. selector_select = selector.select
  249. os_sendfile = os.sendfile
  250. try:
  251. while True:
  252. if timeout and not selector_select(timeout):
  253. raise _socket.timeout('timed out')
  254. if count:
  255. blocksize = count - total_sent
  256. if blocksize <= 0:
  257. break
  258. try:
  259. sent = os_sendfile(sockno, fileno, offset, blocksize)
  260. except BlockingIOError:
  261. if not timeout:
  262. # Block until the socket is ready to send some
  263. # data; avoids hogging CPU resources.
  264. selector_select()
  265. continue
  266. except OSError as err:
  267. if total_sent == 0:
  268. # We can get here for different reasons, the main
  269. # one being 'file' is not a regular mmap(2)-like
  270. # file, in which case we'll fall back on using
  271. # plain send().
  272. raise _GiveupOnSendfile(err)
  273. raise err from None
  274. else:
  275. if sent == 0:
  276. break # EOF
  277. offset += sent
  278. total_sent += sent
  279. return total_sent
  280. finally:
  281. if total_sent > 0 and hasattr(file, 'seek'):
  282. file.seek(offset)
  283. else:
  284. def _sendfile_use_sendfile(self, file, offset=0, count=None):
  285. raise _GiveupOnSendfile(
  286. "os.sendfile() not available on this platform")
  287. def _sendfile_use_send(self, file, offset=0, count=None):
  288. self._check_sendfile_params(file, offset, count)
  289. if self.gettimeout() == 0:
  290. raise ValueError("non-blocking sockets are not supported")
  291. if offset:
  292. file.seek(offset)
  293. blocksize = min(count, 8192) if count else 8192
  294. total_sent = 0
  295. # localize variable access to minimize overhead
  296. file_read = file.read
  297. sock_send = self.send
  298. try:
  299. while True:
  300. if count:
  301. blocksize = min(count - total_sent, blocksize)
  302. if blocksize <= 0:
  303. break
  304. data = memoryview(file_read(blocksize))
  305. if not data:
  306. break # EOF
  307. while True:
  308. try:
  309. sent = sock_send(data)
  310. except BlockingIOError:
  311. continue
  312. else:
  313. total_sent += sent
  314. if sent < len(data):
  315. data = data[sent:]
  316. else:
  317. break
  318. return total_sent
  319. finally:
  320. if total_sent > 0 and hasattr(file, 'seek'):
  321. file.seek(offset + total_sent)
  322. def _check_sendfile_params(self, file, offset, count):
  323. if 'b' not in getattr(file, 'mode', 'b'):
  324. raise ValueError("file should be opened in binary mode")
  325. if not self.type & SOCK_STREAM:
  326. raise ValueError("only SOCK_STREAM type sockets are supported")
  327. if count is not None:
  328. if not isinstance(count, int):
  329. raise TypeError(
  330. "count must be a positive integer (got {!r})".format(count))
  331. if count <= 0:
  332. raise ValueError(
  333. "count must be a positive integer (got {!r})".format(count))
  334. def sendfile(self, file, offset=0, count=None):
  335. """sendfile(file[, offset[, count]]) -> sent
  336. Send a file until EOF is reached by using high-performance
  337. os.sendfile() and return the total number of bytes which
  338. were sent.
  339. *file* must be a regular file object opened in binary mode.
  340. If os.sendfile() is not available (e.g. Windows) or file is
  341. not a regular file socket.send() will be used instead.
  342. *offset* tells from where to start reading the file.
  343. If specified, *count* is the total number of bytes to transmit
  344. as opposed to sending the file until EOF is reached.
  345. File position is updated on return or also in case of error in
  346. which case file.tell() can be used to figure out the number of
  347. bytes which were sent.
  348. The socket must be of SOCK_STREAM type.
  349. Non-blocking sockets are not supported.
  350. """
  351. try:
  352. return self._sendfile_use_sendfile(file, offset, count)
  353. except _GiveupOnSendfile:
  354. return self._sendfile_use_send(file, offset, count)
  355. def _decref_socketios(self):
  356. if self._io_refs > 0:
  357. self._io_refs -= 1
  358. if self._closed:
  359. self.close()
  360. def _real_close(self, _ss=_socket.socket):
  361. # This function should not reference any globals. See issue #808164.
  362. _ss.close(self)
  363. def close(self):
  364. # This function should not reference any globals. See issue #808164.
  365. self._closed = True
  366. if self._io_refs <= 0:
  367. self._real_close()
  368. def detach(self):
  369. """detach() -> file descriptor
  370. Close the socket object without closing the underlying file descriptor.
  371. The object cannot be used after this call, but the file descriptor
  372. can be reused for other purposes. The file descriptor is returned.
  373. """
  374. self._closed = True
  375. return super().detach()
  376. @property
  377. def family(self):
  378. """Read-only access to the address family for this socket.
  379. """
  380. return _intenum_converter(super().family, AddressFamily)
  381. @property
  382. def type(self):
  383. """Read-only access to the socket type.
  384. """
  385. return _intenum_converter(super().type, SocketKind)
  386. if os.name == 'nt':
  387. def get_inheritable(self):
  388. return os.get_handle_inheritable(self.fileno())
  389. def set_inheritable(self, inheritable):
  390. os.set_handle_inheritable(self.fileno(), inheritable)
  391. else:
  392. def get_inheritable(self):
  393. return os.get_inheritable(self.fileno())
  394. def set_inheritable(self, inheritable):
  395. os.set_inheritable(self.fileno(), inheritable)
  396. get_inheritable.__doc__ = "Get the inheritable flag of the socket"
  397. set_inheritable.__doc__ = "Set the inheritable flag of the socket"
  398. def fromfd(fd, family, type, proto=0):
  399. """ fromfd(fd, family, type[, proto]) -> socket object
  400. Create a socket object from a duplicate of the given file
  401. descriptor. The remaining arguments are the same as for socket().
  402. """
  403. nfd = dup(fd)
  404. return socket(family, type, proto, nfd)
  405. if hasattr(_socket.socket, "share"):
  406. def fromshare(info):
  407. """ fromshare(info) -> socket object
  408. Create a socket object from the bytes object returned by
  409. socket.share(pid).
  410. """
  411. return socket(0, 0, 0, info)
  412. __all__.append("fromshare")
  413. if hasattr(_socket, "socketpair"):
  414. def socketpair(family=None, type=SOCK_STREAM, proto=0):
  415. """socketpair([family[, type[, proto]]]) -> (socket object, socket object)
  416. Create a pair of socket objects from the sockets returned by the platform
  417. socketpair() function.
  418. The arguments are the same as for socket() except the default family is
  419. AF_UNIX if defined on the platform; otherwise, the default is AF_INET.
  420. """
  421. if family is None:
  422. try:
  423. family = AF_UNIX
  424. except NameError:
  425. family = AF_INET
  426. a, b = _socket.socketpair(family, type, proto)
  427. a = socket(family, type, proto, a.detach())
  428. b = socket(family, type, proto, b.detach())
  429. return a, b
  430. else:
  431. # Origin: https://gist.github.com/4325783, by Geert Jansen. Public domain.
  432. def socketpair(family=AF_INET, type=SOCK_STREAM, proto=0):
  433. if family == AF_INET:
  434. host = _LOCALHOST
  435. elif family == AF_INET6:
  436. host = _LOCALHOST_V6
  437. else:
  438. raise ValueError("Only AF_INET and AF_INET6 socket address families "
  439. "are supported")
  440. if type != SOCK_STREAM:
  441. raise ValueError("Only SOCK_STREAM socket type is supported")
  442. if proto != 0:
  443. raise ValueError("Only protocol zero is supported")
  444. # We create a connected TCP socket. Note the trick with
  445. # setblocking(False) that prevents us from having to create a thread.
  446. lsock = socket(family, type, proto)
  447. try:
  448. lsock.bind((host, 0))
  449. lsock.listen()
  450. # On IPv6, ignore flow_info and scope_id
  451. addr, port = lsock.getsockname()[:2]
  452. csock = socket(family, type, proto)
  453. try:
  454. csock.setblocking(False)
  455. try:
  456. csock.connect((addr, port))
  457. except (BlockingIOError, InterruptedError):
  458. pass
  459. csock.setblocking(True)
  460. ssock, _ = lsock.accept()
  461. except:
  462. csock.close()
  463. raise
  464. finally:
  465. lsock.close()
  466. return (ssock, csock)
  467. __all__.append("socketpair")
  468. socketpair.__doc__ = """socketpair([family[, type[, proto]]]) -> (socket object, socket object)
  469. Create a pair of socket objects from the sockets returned by the platform
  470. socketpair() function.
  471. The arguments are the same as for socket() except the default family is AF_UNIX
  472. if defined on the platform; otherwise, the default is AF_INET.
  473. """
  474. _blocking_errnos = { EAGAIN, EWOULDBLOCK }
  475. class SocketIO(io.RawIOBase):
  476. """Raw I/O implementation for stream sockets.
  477. This class supports the makefile() method on sockets. It provides
  478. the raw I/O interface on top of a socket object.
  479. """
  480. # One might wonder why not let FileIO do the job instead. There are two
  481. # main reasons why FileIO is not adapted:
  482. # - it wouldn't work under Windows (where you can't used read() and
  483. # write() on a socket handle)
  484. # - it wouldn't work with socket timeouts (FileIO would ignore the
  485. # timeout and consider the socket non-blocking)
  486. # XXX More docs
  487. def __init__(self, sock, mode):
  488. if mode not in ("r", "w", "rw", "rb", "wb", "rwb"):
  489. raise ValueError("invalid mode: %r" % mode)
  490. io.RawIOBase.__init__(self)
  491. self._sock = sock
  492. if "b" not in mode:
  493. mode += "b"
  494. self._mode = mode
  495. self._reading = "r" in mode
  496. self._writing = "w" in mode
  497. self._timeout_occurred = False
  498. def readinto(self, b):
  499. """Read up to len(b) bytes into the writable buffer *b* and return
  500. the number of bytes read. If the socket is non-blocking and no bytes
  501. are available, None is returned.
  502. If *b* is non-empty, a 0 return value indicates that the connection
  503. was shutdown at the other end.
  504. """
  505. self._checkClosed()
  506. self._checkReadable()
  507. if self._timeout_occurred:
  508. raise OSError("cannot read from timed out object")
  509. while True:
  510. try:
  511. return self._sock.recv_into(b)
  512. except timeout:
  513. self._timeout_occurred = True
  514. raise
  515. except error as e:
  516. if e.args[0] in _blocking_errnos:
  517. return None
  518. raise
  519. def write(self, b):
  520. """Write the given bytes or bytearray object *b* to the socket
  521. and return the number of bytes written. This can be less than
  522. len(b) if not all data could be written. If the socket is
  523. non-blocking and no bytes could be written None is returned.
  524. """
  525. self._checkClosed()
  526. self._checkWritable()
  527. try:
  528. return self._sock.send(b)
  529. except error as e:
  530. # XXX what about EINTR?
  531. if e.args[0] in _blocking_errnos:
  532. return None
  533. raise
  534. def readable(self):
  535. """True if the SocketIO is open for reading.
  536. """
  537. if self.closed:
  538. raise ValueError("I/O operation on closed socket.")
  539. return self._reading
  540. def writable(self):
  541. """True if the SocketIO is open for writing.
  542. """
  543. if self.closed:
  544. raise ValueError("I/O operation on closed socket.")
  545. return self._writing
  546. def seekable(self):
  547. """True if the SocketIO is open for seeking.
  548. """
  549. if self.closed:
  550. raise ValueError("I/O operation on closed socket.")
  551. return super().seekable()
  552. def fileno(self):
  553. """Return the file descriptor of the underlying socket.
  554. """
  555. self._checkClosed()
  556. return self._sock.fileno()
  557. @property
  558. def name(self):
  559. if not self.closed:
  560. return self.fileno()
  561. else:
  562. return -1
  563. @property
  564. def mode(self):
  565. return self._mode
  566. def close(self):
  567. """Close the SocketIO object. This doesn't close the underlying
  568. socket, except if all references to it have disappeared.
  569. """
  570. if self.closed:
  571. return
  572. io.RawIOBase.close(self)
  573. self._sock._decref_socketios()
  574. self._sock = None
  575. def getfqdn(name=''):
  576. """Get fully qualified domain name from name.
  577. An empty argument is interpreted as meaning the local host.
  578. First the hostname returned by gethostbyaddr() is checked, then
  579. possibly existing aliases. In case no FQDN is available, hostname
  580. from gethostname() is returned.
  581. """
  582. name = name.strip()
  583. if not name or name == '0.0.0.0':
  584. name = gethostname()
  585. try:
  586. hostname, aliases, ipaddrs = gethostbyaddr(name)
  587. except error:
  588. pass
  589. else:
  590. aliases.insert(0, hostname)
  591. for name in aliases:
  592. if '.' in name:
  593. break
  594. else:
  595. name = hostname
  596. return name
  597. _GLOBAL_DEFAULT_TIMEOUT = object()
  598. def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT,
  599. source_address=None):
  600. """Connect to *address* and return the socket object.
  601. Convenience function. Connect to *address* (a 2-tuple ``(host,
  602. port)``) and return the socket object. Passing the optional
  603. *timeout* parameter will set the timeout on the socket instance
  604. before attempting to connect. If no *timeout* is supplied, the
  605. global default timeout setting returned by :func:`getdefaulttimeout`
  606. is used. If *source_address* is set it must be a tuple of (host, port)
  607. for the socket to bind as a source address before making the connection.
  608. A host of '' or port 0 tells the OS to use the default.
  609. """
  610. host, port = address
  611. err = None
  612. for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  613. af, socktype, proto, canonname, sa = res
  614. sock = None
  615. try:
  616. sock = socket(af, socktype, proto)
  617. if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
  618. sock.settimeout(timeout)
  619. if source_address:
  620. sock.bind(source_address)
  621. sock.connect(sa)
  622. # Break explicitly a reference cycle
  623. err = None
  624. return sock
  625. except error as _:
  626. err = _
  627. if sock is not None:
  628. sock.close()
  629. if err is not None:
  630. try:
  631. raise err
  632. finally:
  633. # Break explicitly a reference cycle
  634. err = None
  635. else:
  636. raise error("getaddrinfo returns an empty list")
  637. def getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
  638. """Resolve host and port into list of address info entries.
  639. Translate the host/port argument into a sequence of 5-tuples that contain
  640. all the necessary arguments for creating a socket connected to that service.
  641. host is a domain name, a string representation of an IPv4/v6 address or
  642. None. port is a string service name such as 'http', a numeric port number or
  643. None. By passing None as the value of host and port, you can pass NULL to
  644. the underlying C API.
  645. The family, type and proto arguments can be optionally specified in order to
  646. narrow the list of addresses returned. Passing zero as a value for each of
  647. these arguments selects the full range of results.
  648. """
  649. # We override this function since we want to translate the numeric family
  650. # and socket type values to enum constants.
  651. addrlist = []
  652. for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
  653. af, socktype, proto, canonname, sa = res
  654. addrlist.append((_intenum_converter(af, AddressFamily),
  655. _intenum_converter(socktype, SocketKind),
  656. proto, canonname, sa))
  657. return addrlist