# 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 [*]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() -- mape 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)ssl() -- secure socket layer support (only available if configured)socket.getdefaulttimeout() -- get the default timeout valuesocket.setdefaulttimeout() -- set the default timeout valuecreate_connection() -- connects to an address, with an optional timeout[*] 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 supportedInteger constants:AF_INET, AF_UNIX -- socket domains (first argument to socket() call)SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)Many other constants may be defined; these may be used in calls tothe setsockopt() and getsockopt() methods."""import _socketfrom _socket import *try:import _sslexcept ImportError:# no SSL supportpasselse:def ssl(sock, keyfile=None, certfile=None):# we do an internal import here because the ssl# module imports the socket moduleimport ssl as _realsslwarnings.warn("socket.ssl() is deprecated. Use ssl.wrap_socket() instead.",DeprecationWarning, stacklevel=2)return _realssl.sslwrap_simple(sock, keyfile, certfile)# we need to import the same constants we used to...from _ssl import SSLError as sslerrorfrom _ssl import \RAND_add, \RAND_egd, \RAND_status, \SSL_ERROR_ZERO_RETURN, \SSL_ERROR_WANT_READ, \SSL_ERROR_WANT_WRITE, \SSL_ERROR_WANT_X509_LOOKUP, \SSL_ERROR_SYSCALL, \SSL_ERROR_SSL, \SSL_ERROR_WANT_CONNECT, \SSL_ERROR_EOF, \SSL_ERROR_INVALID_ERROR_CODEimport os, sys, warningstry:from cStringIO import StringIOexcept ImportError:from StringIO import StringIOtry:from errno import EBADFexcept ImportError:EBADF = 9__all__ = ["getfqdn"]__all__.extend(os._get_exports_list(_socket))_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")def 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_socketmethods = ('bind', 'connect', 'connect_ex', 'fileno', 'listen','getpeername', 'getsockname', 'getsockopt', 'setsockopt','sendall', 'setblocking','settimeout', 'gettimeout', 'shutdown')if os.name == "nt":_socketmethods = _socketmethods + ('ioctl',)if sys.platform == "riscos":_socketmethods = _socketmethods + ('sleeptaskw',)# All the method names that must be delegated to either the real socket# object or the _closedsocket object._delegate_methods = ("recv", "recvfrom", "recv_into", "recvfrom_into","send", "sendto")class _closedsocket(object):__slots__ = []def _dummy(*args):raise error(EBADF, 'Bad file descriptor')# All _delegate_methods must also be initialized here.send = recv = recv_into = sendto = recvfrom = recvfrom_into = _dummy__getattr__ = _dummy# Wrapper around platform socket objects. This implements# a platform-independent dup() functionality. The# implementation currently relies on reference counting# to close the underlying socket object.class _socketobject(object):__doc__ = _realsocket.__doc____slots__ = ["_sock", "__weakref__"] + list(_delegate_methods)def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None):if _sock is None:_sock = _realsocket(family, type, proto)self._sock = _sockfor method in _delegate_methods:setattr(self, method, getattr(_sock, method))def close(self):self._sock = _closedsocket()dummy = self._sock._dummyfor method in _delegate_methods:setattr(self, method, dummy)close.__doc__ = _realsocket.close.__doc__def accept(self):sock, addr = self._sock.accept()return _socketobject(_sock=sock), addraccept.__doc__ = _realsocket.accept.__doc__def dup(self):"""dup() -> socket objectReturn a new socket object connected to the same system resource."""return _socketobject(_sock=self._sock)def makefile(self, mode='r', bufsize=-1):"""makefile([mode[, bufsize]]) -> file objectReturn a regular file object corresponding to the socket. The modeand bufsize arguments are as for the built-in open() function."""return _fileobject(self._sock, mode, bufsize)family = property(lambda self: self._sock.family, doc="the socket family")type = property(lambda self: self._sock.type, doc="the socket type")proto = property(lambda self: self._sock.proto, doc="the socket protocol")_s = ("def %s(self, *args): return self._sock.%s(*args)\n\n""%s.__doc__ = _realsocket.%s.__doc__\n")for _m in _socketmethods:exec _s % (_m, _m, _m, _m)del _m, _ssocket = SocketType = _socketobjectclass _fileobject(object):"""Faux file object attached to a socket object."""default_bufsize = 8192name = "<socket>"__slots__ = ["mode", "bufsize", "softspace",# "closed" is a property, see below"_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf","_close"]def __init__(self, sock, mode='rb', bufsize=-1, close=False):self._sock = sockself.mode = mode # Not actually used in this versionif bufsize < 0:bufsize = self.default_bufsizeself.bufsize = bufsizeself.softspace = False# _rbufsize is the suggested recv buffer size. It is *strictly*# obeyed within readline() for recv calls. If it is larger than# default_bufsize it will be used for recv calls within read().if bufsize == 0:self._rbufsize = 1elif bufsize == 1:self._rbufsize = self.default_bufsizeelse:self._rbufsize = bufsizeself._wbufsize = bufsize# We use StringIO for the read buffer to avoid holding a list# of variously sized string objects which have been known to# fragment the heap due to how they are malloc()ed and often# realloc()ed down much smaller than their original allocation.self._rbuf = StringIO()self._wbuf = [] # A list of stringsself._close = closedef _getclosed(self):return self._sock is Noneclosed = property(_getclosed, doc="True if the file is closed")def close(self):try:if self._sock:self.flush()finally:if self._close:self._sock.close()self._sock = Nonedef __del__(self):try:self.close()except:# close() may fail if __init__ didn't completepassdef flush(self):if self._wbuf:buffer = "".join(self._wbuf)self._wbuf = []self._sock.sendall(buffer)def fileno(self):return self._sock.fileno()def write(self, data):data = str(data) # XXX Should really reject non-string non-buffersif not data:returnself._wbuf.append(data)if (self._wbufsize == 0 orself._wbufsize == 1 and '\n' in data orself._get_wbuf_len() >= self._wbufsize):self.flush()def writelines(self, list):# XXX We could do better here for very long lists# XXX Should really reject non-string non-buffersself._wbuf.extend(filter(None, map(str, list)))if (self._wbufsize <= 1 orself._get_wbuf_len() >= self._wbufsize):self.flush()def _get_wbuf_len(self):buf_len = 0for x in self._wbuf:buf_len += len(x)return buf_lendef read(self, size=-1):# Use max, disallow tiny reads in a loop as they are very inefficient.# We never leave read() with any leftover data from a new recv() call# in our internal buffer.rbufsize = max(self._rbufsize, self.default_bufsize)# Our use of StringIO rather than lists of string objects returned by# recv() minimizes memory usage and fragmentation that occurs when# rbufsize is large compared to the typical return value of recv().buf = self._rbufbuf.seek(0, 2) # seek endif size < 0:# Read until EOFself._rbuf = StringIO() # reset _rbuf. we consume it via buf.while True:data = self._sock.recv(rbufsize)if not data:breakbuf.write(data)return buf.getvalue()else:# Read until size bytes or EOF seen, whichever comes firstbuf_len = buf.tell()if buf_len >= size:# Already have size bytes in our buffer? Extract and return.buf.seek(0)rv = buf.read(size)self._rbuf = StringIO()self._rbuf.write(buf.read())return rvself._rbuf = StringIO() # reset _rbuf. we consume it via buf.while True:left = size - buf_len# recv() will malloc the amount of memory given as its# parameter even though it often returns much less data# than that. The returned data string is short lived# as we copy it into a StringIO and free it. This avoids# fragmentation issues on many platforms.data = self._sock.recv(left)if not data:breakn = len(data)if n == size and not buf_len:# Shortcut. Avoid buffer data copies when:# - We have no data in our buffer.# AND# - Our call to recv returned exactly the# number of bytes we were asked to read.return dataif n == left:buf.write(data)del data # explicit freebreakassert n <= left, "recv(%d) returned %d bytes" % (left, n)buf.write(data)buf_len += ndel data # explicit free#assert buf_len == buf.tell()return buf.getvalue()def readline(self, size=-1):buf = self._rbufbuf.seek(0, 2) # seek endif buf.tell() > 0:# check if we already have it in our bufferbuf.seek(0)bline = buf.readline(size)if bline.endswith('\n') or len(bline) == size:self._rbuf = StringIO()self._rbuf.write(buf.read())return blinedel blineif size < 0:# Read until \n or EOF, whichever comes firstif self._rbufsize <= 1:# Speed up unbuffered casebuf.seek(0)buffers = [buf.read()]self._rbuf = StringIO() # reset _rbuf. we consume it via buf.data = Nonerecv = self._sock.recvwhile data != "\n":data = recv(1)if not data:breakbuffers.append(data)return "".join(buffers)buf.seek(0, 2) # seek endself._rbuf = StringIO() # reset _rbuf. we consume it via buf.while True:data = self._sock.recv(self._rbufsize)if not data:breaknl = data.find('\n')if nl >= 0:nl += 1buf.write(data[:nl])self._rbuf.write(data[nl:])del databreakbuf.write(data)return buf.getvalue()else:# Read until size bytes or \n or EOF seen, whichever comes firstbuf.seek(0, 2) # seek endbuf_len = buf.tell()if buf_len >= size:buf.seek(0)rv = buf.read(size)self._rbuf = StringIO()self._rbuf.write(buf.read())return rvself._rbuf = StringIO() # reset _rbuf. we consume it via buf.while True:data = self._sock.recv(self._rbufsize)if not data:breakleft = size - buf_len# did we just receive a newline?nl = data.find('\n', 0, left)if nl >= 0:nl += 1# save the excess data to _rbufself._rbuf.write(data[nl:])if buf_len:buf.write(data[:nl])breakelse:# Shortcut. Avoid data copy through buf when returning# a substring of our first recv().return data[:nl]n = len(data)if n == size and not buf_len:# Shortcut. Avoid data copy through buf when# returning exactly all of our first recv().return dataif n >= left:buf.write(data[:left])self._rbuf.write(data[left:])breakbuf.write(data)buf_len += n#assert buf_len == buf.tell()return buf.getvalue()def readlines(self, sizehint=0):total = 0list = []while True:line = self.readline()if not line:breaklist.append(line)total += len(line)if sizehint and total >= sizehint:breakreturn list# Iterator protocolsdef __iter__(self):return selfdef next(self):line = self.readline()if not line:raise StopIterationreturn line_GLOBAL_DEFAULT_TIMEOUT = object()def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT):"""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."""msg = "getaddrinfo returns an empty list"host, port = addressfor 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)sock.connect(sa)return sockexcept error, msg:if sock is not None:sock.close()raise error, msg
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。