0001 # Wrapper module for _socket, providing some additional facilities 0002 # implemented in Python. 0003 0004 """\ 0005 This module provides socket operations and some related functions. 0006 On Unix, it supports IP (Internet Protocol) and Unix domain sockets. 0007 On other systems, it only supports IP. Functions specific for a 0008 socket are available as methods of the socket object. 0009 0010 Functions: 0011 0012 socket() -- create a new socket object 0013 socketpair() -- create a pair of new socket objects [*] 0014 fromfd() -- create a socket object from an open file descriptor [*] 0015 gethostname() -- return the current hostname 0016 gethostbyname() -- map a hostname to its IP number 0017 gethostbyaddr() -- map an IP number or hostname to DNS info 0018 getservbyname() -- map a service name and a protocol name to a port number 0019 getprotobyname() -- mape a protocol name (e.g. 'tcp') to a number 0020 ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order 0021 htons(), htonl() -- convert 16, 32 bit int from host to network byte order 0022 inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format 0023 inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89) 0024 ssl() -- secure socket layer support (only available if configured) 0025 socket.getdefaulttimeout() -- get the default timeout value 0026 socket.setdefaulttimeout() -- set the default timeout value 0027 0028 [*] not available on all platforms! 0029 0030 Special objects: 0031 0032 SocketType -- type object for socket objects 0033 error -- exception raised for I/O errors 0034 has_ipv6 -- boolean value indicating if IPv6 is supported 0035 0036 Integer constants: 0037 0038 AF_INET, AF_UNIX -- socket domains (first argument to socket() call) 0039 SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument) 0040 0041 Many other constants may be defined; these may be used in calls to 0042 the setsockopt() and getsockopt() methods. 0043 """ 0044 0045 import _socket 0046 from _socket import * 0047 0048 _have_ssl = False 0049 try: 0050 import _ssl 0051 from _ssl import * 0052 _have_ssl = True 0053 except ImportError: 0054 pass 0055 0056 import os, sys 0057 0058 try: 0059 from errno import EBADF 0060 except ImportError: 0061 EBADF = 9 0062 0063 __all__ = ["getfqdn"] 0064 __all__.extend(os._get_exports_list(_socket)) 0065 if _have_ssl: 0066 __all__.extend(os._get_exports_list(_ssl)) 0067 0068 _realsocket = socket 0069 if _have_ssl: 0070 _realssl = ssl 0071 def ssl(sock, keyfile=None, certfile=None): 0072 if hasattr(sock, "_sock"): 0073 sock = sock._sock 0074 return _realssl(sock, keyfile, certfile) 0075 0076 # WSA error codes 0077 if sys.platform.lower().startswith("win"): 0078 errorTab = {} 0079 errorTab[10004] = "The operation was interrupted." 0080 errorTab[10009] = "A bad file handle was passed." 0081 errorTab[10013] = "Permission denied." 0082 errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT 0083 errorTab[10022] = "An invalid operation was attempted." 0084 errorTab[10035] = "The socket operation would block" 0085 errorTab[10036] = "A blocking operation is already in progress." 0086 errorTab[10048] = "The network address is in use." 0087 errorTab[10054] = "The connection has been reset." 0088 errorTab[10058] = "The network has been shut down." 0089 errorTab[10060] = "The operation timed out." 0090 errorTab[10061] = "Connection refused." 0091 errorTab[10063] = "The name is too long." 0092 errorTab[10064] = "The host is down." 0093 errorTab[10065] = "The host is unreachable." 0094 __all__.append("errorTab") 0095 0096 0097 0098 def getfqdn(name=''): 0099 """Get fully qualified domain name from name. 0100 0101 An empty argument is interpreted as meaning the local host. 0102 0103 First the hostname returned by gethostbyaddr() is checked, then 0104 possibly existing aliases. In case no FQDN is available, hostname 0105 is returned. 0106 """ 0107 name = name.strip() 0108 if not name or name == '0.0.0.0': 0109 name = gethostname() 0110 try: 0111 hostname, aliases, ipaddrs = gethostbyaddr(name) 0112 except error: 0113 pass 0114 else: 0115 aliases.insert(0, hostname) 0116 for name in aliases: 0117 if '.' in name: 0118 break 0119 else: 0120 name = hostname 0121 return name 0122 0123 0124 # 0125 # These classes are used by the socket() defined on Windows and BeOS 0126 # platforms to provide a best-effort implementation of the cleanup 0127 # semantics needed when sockets can't be dup()ed. 0128 # 0129 # These are not actually used on other platforms. 0130 # 0131 0132 _socketmethods = ( 0133 'bind', 'connect', 'connect_ex', 'fileno', 'listen', 0134 'getpeername', 'getsockname', 'getsockopt', 'setsockopt', 0135 'sendall', 'setblocking', 0136 'settimeout', 'gettimeout', 'shutdown') 0137 0138 if sys.platform == "riscos": 0139 _socketmethods = _socketmethods + ('sleeptaskw',) 0140 0141 class _closedsocket(object): 0142 __slots__ = [] 0143 def _dummy(*args): 0144 raise error(EBADF, 'Bad file descriptor') 0145 send = recv = sendto = recvfrom = __getattr__ = _dummy 0146 0147 class _socketobject(object): 0148 0149 __doc__ = _realsocket.__doc__ 0150 0151 __slots__ = ["_sock", "send", "recv", "sendto", "recvfrom", 0152 "__weakref__"] 0153 0154 def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None): 0155 if _sock is None: 0156 _sock = _realsocket(family, type, proto) 0157 self._sock = _sock 0158 self.send = self._sock.send 0159 self.recv = self._sock.recv 0160 self.sendto = self._sock.sendto 0161 self.recvfrom = self._sock.recvfrom 0162 0163 def close(self): 0164 self._sock = _closedsocket() 0165 self.send = self.recv = self.sendto = self.recvfrom = self._sock._dummy 0166 close.__doc__ = _realsocket.close.__doc__ 0167 0168 def accept(self): 0169 sock, addr = self._sock.accept() 0170 return _socketobject(_sock=sock), addr 0171 accept.__doc__ = _realsocket.accept.__doc__ 0172 0173 def dup(self): 0174 """dup() -> socket object 0175 0176 Return a new socket object connected to the same system resource.""" 0177 return _socketobject(_sock=self._sock) 0178 0179 def makefile(self, mode='r', bufsize=-1): 0180 """makefile([mode[, bufsize]]) -> file object 0181 0182 Return a regular file object corresponding to the socket. The mode 0183 and bufsize arguments are as for the built-in open() function.""" 0184 return _fileobject(self._sock, mode, bufsize) 0185 0186 _s = ("def %s(self, *args): return self._sock.%s(*args)\n\n" 0187 "%s.__doc__ = _realsocket.%s.__doc__\n") 0188 for _m in _socketmethods: 0189 exec _s % (_m, _m, _m, _m) 0190 del _m, _s 0191 0192 socket = SocketType = _socketobject 0193 0194 class _fileobject(object): 0195 """Faux file object attached to a socket object.""" 0196 0197 default_bufsize = 8192 0198 name = "<socket>" 0199 0200 __slots__ = ["mode", "bufsize", "softspace", 0201 # "closed" is a property, see below 0202 "_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf"] 0203 0204 def __init__(self, sock, mode='rb', bufsize=-1): 0205 self._sock = sock 0206 self.mode = mode # Not actually used in this version 0207 if bufsize < 0: 0208 bufsize = self.default_bufsize 0209 self.bufsize = bufsize 0210 self.softspace = False 0211 if bufsize == 0: 0212 self._rbufsize = 1 0213 elif bufsize == 1: 0214 self._rbufsize = self.default_bufsize 0215 else: 0216 self._rbufsize = bufsize 0217 self._wbufsize = bufsize 0218 self._rbuf = "" # A string 0219 self._wbuf = [] # A list of strings 0220 0221 def _getclosed(self): 0222 return self._sock is None 0223 closed = property(_getclosed, doc="True if the file is closed") 0224 0225 def close(self): 0226 try: 0227 if self._sock: 0228 self.flush() 0229 finally: 0230 self._sock = None 0231 0232 def __del__(self): 0233 try: 0234 self.close() 0235 except: 0236 # close() may fail if __init__ didn't complete 0237 pass 0238 0239 def flush(self): 0240 if self._wbuf: 0241 buffer = "".join(self._wbuf) 0242 self._wbuf = [] 0243 self._sock.sendall(buffer) 0244 0245 def fileno(self): 0246 return self._sock.fileno() 0247 0248 def write(self, data): 0249 data = str(data) # XXX Should really reject non-string non-buffers 0250 if not data: 0251 return 0252 self._wbuf.append(data) 0253 if (self._wbufsize == 0 or 0254 self._wbufsize == 1 and '\n' in data or 0255 self._get_wbuf_len() >= self._wbufsize): 0256 self.flush() 0257 0258 def writelines(self, list): 0259 # XXX We could do better here for very long lists 0260 # XXX Should really reject non-string non-buffers 0261 self._wbuf.extend(filter(None, map(str, list))) 0262 if (self._wbufsize <= 1 or 0263 self._get_wbuf_len() >= self._wbufsize): 0264 self.flush() 0265 0266 def _get_wbuf_len(self): 0267 buf_len = 0 0268 for x in self._wbuf: 0269 buf_len += len(x) 0270 return buf_len 0271 0272 def read(self, size=-1): 0273 data = self._rbuf 0274 if size < 0: 0275 # Read until EOF 0276 buffers = [] 0277 if data: 0278 buffers.append(data) 0279 self._rbuf = "" 0280 if self._rbufsize <= 1: 0281 recv_size = self.default_bufsize 0282 else: 0283 recv_size = self._rbufsize 0284 while True: 0285 data = self._sock.recv(recv_size) 0286 if not data: 0287 break 0288 buffers.append(data) 0289 return "".join(buffers) 0290 else: 0291 # Read until size bytes or EOF seen, whichever comes first 0292 buf_len = len(data) 0293 if buf_len >= size: 0294 self._rbuf = data[size:] 0295 return data[:size] 0296 buffers = [] 0297 if data: 0298 buffers.append(data) 0299 self._rbuf = "" 0300 while True: 0301 left = size - buf_len 0302 recv_size = max(self._rbufsize, left) 0303 data = self._sock.recv(recv_size) 0304 if not data: 0305 break 0306 buffers.append(data) 0307 n = len(data) 0308 if n >= left: 0309 self._rbuf = data[left:] 0310 buffers[-1] = data[:left] 0311 break 0312 buf_len += n 0313 return "".join(buffers) 0314 0315 def readline(self, size=-1): 0316 data = self._rbuf 0317 if size < 0: 0318 # Read until \n or EOF, whichever comes first 0319 if self._rbufsize <= 1: 0320 # Speed up unbuffered case 0321 assert data == "" 0322 buffers = [] 0323 recv = self._sock.recv 0324 while data != "\n": 0325 data = recv(1) 0326 if not data: 0327 break 0328 buffers.append(data) 0329 return "".join(buffers) 0330 nl = data.find('\n') 0331 if nl >= 0: 0332 nl += 1 0333 self._rbuf = data[nl:] 0334 return data[:nl] 0335 buffers = [] 0336 if data: 0337 buffers.append(data) 0338 self._rbuf = "" 0339 while True: 0340 data = self._sock.recv(self._rbufsize) 0341 if not data: 0342 break 0343 buffers.append(data) 0344 nl = data.find('\n') 0345 if nl >= 0: 0346 nl += 1 0347 self._rbuf = data[nl:] 0348 buffers[-1] = data[:nl] 0349 break 0350 return "".join(buffers) 0351 else: 0352 # Read until size bytes or \n or EOF seen, whichever comes first 0353 nl = data.find('\n', 0, size) 0354 if nl >= 0: 0355 nl += 1 0356 self._rbuf = data[nl:] 0357 return data[:nl] 0358 buf_len = len(data) 0359 if buf_len >= size: 0360 self._rbuf = data[size:] 0361 return data[:size] 0362 buffers = [] 0363 if data: 0364 buffers.append(data) 0365 self._rbuf = "" 0366 while True: 0367 data = self._sock.recv(self._rbufsize) 0368 if not data: 0369 break 0370 buffers.append(data) 0371 left = size - buf_len 0372 nl = data.find('\n', 0, left) 0373 if nl >= 0: 0374 nl += 1 0375 self._rbuf = data[nl:] 0376 buffers[-1] = data[:nl] 0377 break 0378 n = len(data) 0379 if n >= left: 0380 self._rbuf = data[left:] 0381 buffers[-1] = data[:left] 0382 break 0383 buf_len += n 0384 return "".join(buffers) 0385 0386 def readlines(self, sizehint=0): 0387 total = 0 0388 list = [] 0389 while True: 0390 line = self.readline() 0391 if not line: 0392 break 0393 list.append(line) 0394 total += len(line) 0395 if sizehint and total >= sizehint: 0396 break 0397 return list 0398 0399 # Iterator protocols 0400 0401 def __iter__(self): 0402 return self 0403 0404 def next(self): 0405 line = self.readline() 0406 if not line: 0407 raise StopIteration 0408 return line 0409
Generated by PyXR 0.9.4