# Wrapper module for _socket, providing some additional facilities# implemented in Python."""\This module provides socket operations and some related functions.On Unix, it supports IP (Internet Protocol) and Unix domain sockets.On other systems, it only supports IP. Functions specific for asocket are available as methods of the socket object.Functions:socket() -- create a new socket objectsocketpair() -- create a pair of new socket objects [*]fromfd() -- create a socket object from an open file descriptor [*]fromshare() -- create a socket object from data received from socket.share() [*]gethostname() -- return the current hostnamegethostbyname() -- map a hostname to its IP numbergethostbyaddr() -- map an IP number or hostname to DNS infogetservbyname() -- map a service name and a protocol name to a port numbergetprotobyname() -- map a protocol name (e.g. 'tcp') to a numberntohs(), ntohl() -- convert 16, 32 bit int from network to host byte orderhtons(), htonl() -- convert 16, 32 bit int from host to network byte orderinet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed formatinet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89)socket.getdefaulttimeout() -- get the default timeout valuesocket.setdefaulttimeout() -- set the default timeout valuecreate_connection() -- connects to an address, with an optional timeout andoptional source address.[*] not available on all platforms!Special objects:SocketType -- type object for socket objectserror -- exception raised for I/O errorshas_ipv6 -- boolean value indicating if IPv6 is supportedIntEnum constants:AF_INET, AF_UNIX -- socket domains (first argument to socket() call)SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)Integer constants:Many other constants may be defined; these may be used in calls tothe setsockopt() and getsockopt() methods."""import _socketfrom _socket import *import os, sys, iofrom enum import IntEnumtry:import errnoexcept ImportError:errno = NoneEBADF = getattr(errno, 'EBADF', 9)EAGAIN = getattr(errno, 'EAGAIN', 11)EWOULDBLOCK = getattr(errno, 'EWOULDBLOCK', 11)__all__ = ["fromfd", "getfqdn", "create_connection","AddressFamily", "SocketKind"]__all__.extend(os._get_exports_list(_socket))# Set up the socket.AF_* socket.SOCK_* constants as members of IntEnums for# nicer string representations.# Note that _socket only knows about the integer values. The public interface# in this module understands the enums and translates them back from integers# where needed (e.g. .family property of a socket object).AddressFamily = IntEnum('AddressFamily',{name: value for name, value in globals().items()if name.isupper() and name.startswith('AF_')})globals().update(AddressFamily.__members__)SocketKind = IntEnum('SocketKind',{name: value for name, value in globals().items()if name.isupper() and name.startswith('SOCK_')})globals().update(SocketKind.__members__)def _intenum_converter(value, enum_klass):"""Convert a numeric family value to an IntEnum member.If it's not a known member, return the numeric value itself."""try:return enum_klass(value)except ValueError:return value_realsocket = socket# WSA error codesif sys.platform.lower().startswith("win"):errorTab = {}errorTab[10004] = "The operation was interrupted."errorTab[10009] = "A bad file handle was passed."errorTab[10013] = "Permission denied."errorTab[10014] = "A fault occurred on the network??" # WSAEFAULTerrorTab[10022] = "An invalid operation was attempted."errorTab[10035] = "The socket operation would block"errorTab[10036] = "A blocking operation is already in progress."errorTab[10048] = "The network address is in use."errorTab[10054] = "The connection has been reset."errorTab[10058] = "The network has been shut down."errorTab[10060] = "The operation timed out."errorTab[10061] = "Connection refused."errorTab[10063] = "The name is too long."errorTab[10064] = "The host is down."errorTab[10065] = "The host is unreachable."__all__.append("errorTab")class socket(_socket.socket):"""A subclass of _socket.socket adding the makefile() method."""__slots__ = ["__weakref__", "_io_refs", "_closed"]def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None):# For user code address family and type values are IntEnum members, but# for the underlying _socket.socket they're just integers. The# constructor of _socket.socket converts the given argument to an# integer automatically._socket.socket.__init__(self, family, type, proto, fileno)self._io_refs = 0self._closed = Falsedef __enter__(self):return selfdef __exit__(self, *args):if not self._closed:self.close()def __repr__(self):"""Wrap __repr__() to reveal the real class name and socketaddress(es)."""closed = getattr(self, '_closed', False)s = "<%s.%s%s fd=%i, family=%s, type=%s, proto=%i" \% (self.__class__.__module__,self.__class__.__name__," [closed]" if closed else "",self.fileno(),self.family,self.type,self.proto)if not closed:try:laddr = self.getsockname()if laddr:s += ", laddr=%s" % str(laddr)except error:passtry:raddr = self.getpeername()if raddr:s += ", raddr=%s" % str(raddr)except error:passs += '>'return sdef __getstate__(self):raise TypeError("Cannot serialize socket object")def dup(self):"""dup() -> socket objectDuplicate the socket. Return a new socket object connected to the samesystem resource. The new socket is non-inheritable."""fd = dup(self.fileno())sock = self.__class__(self.family, self.type, self.proto, fileno=fd)sock.settimeout(self.gettimeout())return sockdef accept(self):"""accept() -> (socket object, address info)Wait for an incoming connection. Return a new socketrepresenting the connection, and the address of the client.For IP sockets, the address info is a pair (hostaddr, port)."""fd, addr = self._accept()sock = socket(self.family, self.type, self.proto, fileno=fd)# Issue #7995: if no default timeout is set and the listening# socket had a (non-zero) timeout, force the new socket in blocking# mode to override platform-specific socket flags inheritance.if getdefaulttimeout() is None and self.gettimeout():sock.setblocking(True)return sock, addrdef makefile(self, mode="r", buffering=None, *,encoding=None, errors=None, newline=None):"""makefile(...) -> an I/O stream connected to the socketThe arguments are as for io.open() after the filename,except the only mode characters supported are 'r', 'w' and 'b'.The semantics are similar too. (XXX refactor to share code?)"""if not set(mode) <= {"r", "w", "b"}:raise ValueError("invalid mode %r (only r, w, b allowed)" % (mode,))writing = "w" in modereading = "r" in mode or not writingassert reading or writingbinary = "b" in moderawmode = ""if reading:rawmode += "r"if writing:rawmode += "w"raw = SocketIO(self, rawmode)self._io_refs += 1if buffering is None:buffering = -1if buffering < 0:buffering = io.DEFAULT_BUFFER_SIZEif buffering == 0:if not binary:raise ValueError("unbuffered streams must be binary")return rawif reading and writing:buffer = io.BufferedRWPair(raw, raw, buffering)elif reading:buffer = io.BufferedReader(raw, buffering)else:assert writingbuffer = io.BufferedWriter(raw, buffering)if binary:return buffertext = io.TextIOWrapper(buffer, encoding, errors, newline)text.mode = modereturn textdef _decref_socketios(self):if self._io_refs > 0:self._io_refs -= 1if self._closed:self.close()def _real_close(self, _ss=_socket.socket):# This function should not reference any globals. See issue #808164._ss.close(self)def close(self):# This function should not reference any globals. See issue #808164.self._closed = Trueif self._io_refs <= 0:self._real_close()def detach(self):"""detach() -> file descriptorClose the socket object without closing the underlying file descriptor.The object cannot be used after this call, but the file descriptorcan be reused for other purposes. The file descriptor is returned."""self._closed = Truereturn super().detach()@propertydef family(self):"""Read-only access to the address family for this socket."""return _intenum_converter(super().family, AddressFamily)@propertydef type(self):"""Read-only access to the socket type."""return _intenum_converter(super().type, SocketKind)if os.name == 'nt':def get_inheritable(self):return os.get_handle_inheritable(self.fileno())def set_inheritable(self, inheritable):os.set_handle_inheritable(self.fileno(), inheritable)else:def get_inheritable(self):return os.get_inheritable(self.fileno())def set_inheritable(self, inheritable):os.set_inheritable(self.fileno(), inheritable)get_inheritable.__doc__ = "Get the inheritable flag of the socket"set_inheritable.__doc__ = "Set the inheritable flag of the socket"def fromfd(fd, family, type, proto=0):""" fromfd(fd, family, type[, proto]) -> socket objectCreate a socket object from a duplicate of the given filedescriptor. The remaining arguments are the same as for socket()."""nfd = dup(fd)return socket(family, type, proto, nfd)if hasattr(_socket.socket, "share"):def fromshare(info):""" fromshare(info) -> socket objectCreate a socket object from the bytes object returned bysocket.share(pid)."""return socket(0, 0, 0, info)__all__.append("fromshare")if hasattr(_socket, "socketpair"):def socketpair(family=None, type=SOCK_STREAM, proto=0):"""socketpair([family[, type[, proto]]]) -> (socket object, socket object)Create a pair of socket objects from the sockets returned by the platformsocketpair() function.The arguments are the same as for socket() except the default family isAF_UNIX if defined on the platform; otherwise, the default is AF_INET."""if family is None:try:family = AF_UNIXexcept NameError:family = AF_INETa, b = _socket.socketpair(family, type, proto)a = socket(family, type, proto, a.detach())b = socket(family, type, proto, b.detach())return a, b_blocking_errnos = { EAGAIN, EWOULDBLOCK }class SocketIO(io.RawIOBase):"""Raw I/O implementation for stream sockets.This class supports the makefile() method on sockets. It providesthe raw I/O interface on top of a socket object."""# One might wonder why not let FileIO do the job instead. There are two# main reasons why FileIO is not adapted:# - it wouldn't work under Windows (where you can't used read() and# write() on a socket handle)# - it wouldn't work with socket timeouts (FileIO would ignore the# timeout and consider the socket non-blocking)# XXX More docsdef __init__(self, sock, mode):if mode not in ("r", "w", "rw", "rb", "wb", "rwb"):raise ValueError("invalid mode: %r" % mode)io.RawIOBase.__init__(self)self._sock = sockif "b" not in mode:mode += "b"self._mode = modeself._reading = "r" in modeself._writing = "w" in modeself._timeout_occurred = Falsedef readinto(self, b):"""Read up to len(b) bytes into the writable buffer *b* and returnthe number of bytes read. If the socket is non-blocking and no bytesare available, None is returned.If *b* is non-empty, a 0 return value indicates that the connectionwas shutdown at the other end."""self._checkClosed()self._checkReadable()if self._timeout_occurred:raise OSError("cannot read from timed out object")while True:try:return self._sock.recv_into(b)except timeout:self._timeout_occurred = Trueraiseexcept InterruptedError:continueexcept error as e:if e.args[0] in _blocking_errnos:return Noneraisedef write(self, b):"""Write the given bytes or bytearray object *b* to the socketand return the number of bytes written. This can be less thanlen(b) if not all data could be written. If the socket isnon-blocking and no bytes could be written None is returned."""self._checkClosed()self._checkWritable()try:return self._sock.send(b)except error as e:# XXX what about EINTR?if e.args[0] in _blocking_errnos:return Noneraisedef readable(self):"""True if the SocketIO is open for reading."""if self.closed:raise ValueError("I/O operation on closed socket.")return self._readingdef writable(self):"""True if the SocketIO is open for writing."""if self.closed:raise ValueError("I/O operation on closed socket.")return self._writingdef seekable(self):"""True if the SocketIO is open for seeking."""if self.closed:raise ValueError("I/O operation on closed socket.")return super().seekable()def fileno(self):"""Return the file descriptor of the underlying socket."""self._checkClosed()return self._sock.fileno()@propertydef name(self):if not self.closed:return self.fileno()else:return -1@propertydef mode(self):return self._modedef close(self):"""Close the SocketIO object. This doesn't close the underlyingsocket, except if all references to it have disappeared."""if self.closed:returnio.RawIOBase.close(self)self._sock._decref_socketios()self._sock = Nonedef getfqdn(name=''):"""Get fully qualified domain name from name.An empty argument is interpreted as meaning the local host.First the hostname returned by gethostbyaddr() is checked, thenpossibly existing aliases. In case no FQDN is available, hostnamefrom gethostname() is returned."""name = name.strip()if not name or name == '0.0.0.0':name = gethostname()try:hostname, aliases, ipaddrs = gethostbyaddr(name)except error:passelse:aliases.insert(0, hostname)for name in aliases:if '.' in name:breakelse:name = hostnamereturn name_GLOBAL_DEFAULT_TIMEOUT = object()def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT,source_address=None):"""Connect to *address* and return the socket object.Convenience function. Connect to *address* (a 2-tuple ``(host,port)``) and return the socket object. Passing the optional*timeout* parameter will set the timeout on the socket instancebefore attempting to connect. If no *timeout* is supplied, theglobal default timeout setting returned by :func:`getdefaulttimeout`is used. If *source_address* is set it must be a tuple of (host, port)for the socket to bind as a source address before making the connection.An host of '' or port 0 tells the OS to use the default."""host, port = addresserr = Nonefor res in getaddrinfo(host, port, 0, SOCK_STREAM):af, socktype, proto, canonname, sa = ressock = Nonetry:sock = socket(af, socktype, proto)if timeout is not _GLOBAL_DEFAULT_TIMEOUT:sock.settimeout(timeout)if source_address:sock.bind(source_address)sock.connect(sa)return sockexcept error as _:err = _if sock is not None:sock.close()if err is not None:raise errelse:raise error("getaddrinfo returns an empty list")def getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):"""Resolve host and port into list of address info entries.Translate the host/port argument into a sequence of 5-tuples that containall the necessary arguments for creating a socket connected to that service.host is a domain name, a string representation of an IPv4/v6 address orNone. port is a string service name such as 'http', a numeric port number orNone. By passing None as the value of host and port, you can pass NULL tothe underlying C API.The family, type and proto arguments can be optionally specified in order tonarrow the list of addresses returned. Passing zero as a value for each ofthese arguments selects the full range of results."""# We override this function since we want to translate the numeric family# and socket type values to enum constants.addrlist = []for res in _socket.getaddrinfo(host, port, family, type, proto, flags):af, socktype, proto, canonname, sa = resaddrlist.append((_intenum_converter(af, AddressFamily),_intenum_converter(socktype, SocketKind),proto, canonname, sa))return addrlist
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。
1. Open source ecosystem
2. Collaboration, People, Software
3. Evaluation model