ยปCore Development>Code coverage>Lib/socket.py

Python code coverage for Lib/socket.py

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