Propagate exceptions from shutdown() if raiseExceptions is not set.
[python.git] / Lib / socket.py
blobee2457fa0c12f7f8ee25b25b891bec713a0a5533
1 # Wrapper module for _socket, providing some additional facilities
2 # implemented in Python.
4 """\
5 This module provides socket operations and some related functions.
6 On Unix, it supports IP (Internet Protocol) and Unix domain sockets.
7 On other systems, it only supports IP. Functions specific for a
8 socket are available as methods of the socket object.
10 Functions:
12 socket() -- create a new socket object
13 socketpair() -- create a pair of new socket objects [*]
14 fromfd() -- create a socket object from an open file descriptor [*]
15 gethostname() -- return the current hostname
16 gethostbyname() -- map a hostname to its IP number
17 gethostbyaddr() -- map an IP number or hostname to DNS info
18 getservbyname() -- map a service name and a protocol name to a port number
19 getprotobyname() -- mape a protocol name (e.g. 'tcp') to a number
20 ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order
21 htons(), htonl() -- convert 16, 32 bit int from host to network byte order
22 inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format
23 inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89)
24 ssl() -- secure socket layer support (only available if configured)
25 socket.getdefaulttimeout() -- get the default timeout value
26 socket.setdefaulttimeout() -- set the default timeout value
28 [*] not available on all platforms!
30 Special objects:
32 SocketType -- type object for socket objects
33 error -- exception raised for I/O errors
34 has_ipv6 -- boolean value indicating if IPv6 is supported
36 Integer constants:
38 AF_INET, AF_UNIX -- socket domains (first argument to socket() call)
39 SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)
41 Many other constants may be defined; these may be used in calls to
42 the setsockopt() and getsockopt() methods.
43 """
45 import _socket
46 from _socket import *
48 _have_ssl = False
49 try:
50 import _ssl
51 from _ssl import *
52 _have_ssl = True
53 except ImportError:
54 pass
56 import os, sys
58 try:
59 from errno import EBADF
60 except ImportError:
61 EBADF = 9
63 __all__ = ["getfqdn"]
64 __all__.extend(os._get_exports_list(_socket))
65 if _have_ssl:
66 __all__.extend(os._get_exports_list(_ssl))
68 _realsocket = socket
69 if _have_ssl:
70 _realssl = ssl
71 def ssl(sock, keyfile=None, certfile=None):
72 if hasattr(sock, "_sock"):
73 sock = sock._sock
74 return _realssl(sock, keyfile, certfile)
76 # WSA error codes
77 if sys.platform.lower().startswith("win"):
78 errorTab = {}
79 errorTab[10004] = "The operation was interrupted."
80 errorTab[10009] = "A bad file handle was passed."
81 errorTab[10013] = "Permission denied."
82 errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT
83 errorTab[10022] = "An invalid operation was attempted."
84 errorTab[10035] = "The socket operation would block"
85 errorTab[10036] = "A blocking operation is already in progress."
86 errorTab[10048] = "The network address is in use."
87 errorTab[10054] = "The connection has been reset."
88 errorTab[10058] = "The network has been shut down."
89 errorTab[10060] = "The operation timed out."
90 errorTab[10061] = "Connection refused."
91 errorTab[10063] = "The name is too long."
92 errorTab[10064] = "The host is down."
93 errorTab[10065] = "The host is unreachable."
94 __all__.append("errorTab")
98 def getfqdn(name=''):
99 """Get fully qualified domain name from name.
101 An empty argument is interpreted as meaning the local host.
103 First the hostname returned by gethostbyaddr() is checked, then
104 possibly existing aliases. In case no FQDN is available, hostname
105 from gethostname() is returned.
107 name = name.strip()
108 if not name or name == '0.0.0.0':
109 name = gethostname()
110 try:
111 hostname, aliases, ipaddrs = gethostbyaddr(name)
112 except error:
113 pass
114 else:
115 aliases.insert(0, hostname)
116 for name in aliases:
117 if '.' in name:
118 break
119 else:
120 name = hostname
121 return name
125 # These classes are used by the socket() defined on Windows and BeOS
126 # platforms to provide a best-effort implementation of the cleanup
127 # semantics needed when sockets can't be dup()ed.
129 # These are not actually used on other platforms.
132 _socketmethods = (
133 'bind', 'connect', 'connect_ex', 'fileno', 'listen',
134 'getpeername', 'getsockname', 'getsockopt', 'setsockopt',
135 'sendall', 'setblocking',
136 'settimeout', 'gettimeout', 'shutdown')
138 if sys.platform == "riscos":
139 _socketmethods = _socketmethods + ('sleeptaskw',)
141 class _closedsocket(object):
142 __slots__ = []
143 def _dummy(*args):
144 raise error(EBADF, 'Bad file descriptor')
145 send = recv = sendto = recvfrom = __getattr__ = _dummy
147 class _socketobject(object):
149 __doc__ = _realsocket.__doc__
151 __slots__ = ["_sock", "send", "recv", "sendto", "recvfrom",
152 "__weakref__"]
154 def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None):
155 if _sock is None:
156 _sock = _realsocket(family, type, proto)
157 self._sock = _sock
158 self.send = self._sock.send
159 self.recv = self._sock.recv
160 self.sendto = self._sock.sendto
161 self.recvfrom = self._sock.recvfrom
163 def close(self):
164 self._sock = _closedsocket()
165 self.send = self.recv = self.sendto = self.recvfrom = self._sock._dummy
166 close.__doc__ = _realsocket.close.__doc__
168 def accept(self):
169 sock, addr = self._sock.accept()
170 return _socketobject(_sock=sock), addr
171 accept.__doc__ = _realsocket.accept.__doc__
173 def dup(self):
174 """dup() -> socket object
176 Return a new socket object connected to the same system resource."""
177 return _socketobject(_sock=self._sock)
179 def makefile(self, mode='r', bufsize=-1):
180 """makefile([mode[, bufsize]]) -> file object
182 Return a regular file object corresponding to the socket. The mode
183 and bufsize arguments are as for the built-in open() function."""
184 return _fileobject(self._sock, mode, bufsize)
186 _s = ("def %s(self, *args): return self._sock.%s(*args)\n\n"
187 "%s.__doc__ = _realsocket.%s.__doc__\n")
188 for _m in _socketmethods:
189 exec _s % (_m, _m, _m, _m)
190 del _m, _s
192 socket = SocketType = _socketobject
194 class _fileobject(object):
195 """Faux file object attached to a socket object."""
197 default_bufsize = 8192
198 name = "<socket>"
200 __slots__ = ["mode", "bufsize", "softspace",
201 # "closed" is a property, see below
202 "_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf"]
204 def __init__(self, sock, mode='rb', bufsize=-1):
205 self._sock = sock
206 self.mode = mode # Not actually used in this version
207 if bufsize < 0:
208 bufsize = self.default_bufsize
209 self.bufsize = bufsize
210 self.softspace = False
211 if bufsize == 0:
212 self._rbufsize = 1
213 elif bufsize == 1:
214 self._rbufsize = self.default_bufsize
215 else:
216 self._rbufsize = bufsize
217 self._wbufsize = bufsize
218 self._rbuf = "" # A string
219 self._wbuf = [] # A list of strings
221 def _getclosed(self):
222 return self._sock is None
223 closed = property(_getclosed, doc="True if the file is closed")
225 def close(self):
226 try:
227 if self._sock:
228 self.flush()
229 finally:
230 self._sock = None
232 def __del__(self):
233 try:
234 self.close()
235 except:
236 # close() may fail if __init__ didn't complete
237 pass
239 def flush(self):
240 if self._wbuf:
241 buffer = "".join(self._wbuf)
242 self._wbuf = []
243 self._sock.sendall(buffer)
245 def fileno(self):
246 return self._sock.fileno()
248 def write(self, data):
249 data = str(data) # XXX Should really reject non-string non-buffers
250 if not data:
251 return
252 self._wbuf.append(data)
253 if (self._wbufsize == 0 or
254 self._wbufsize == 1 and '\n' in data or
255 self._get_wbuf_len() >= self._wbufsize):
256 self.flush()
258 def writelines(self, list):
259 # XXX We could do better here for very long lists
260 # XXX Should really reject non-string non-buffers
261 self._wbuf.extend(filter(None, map(str, list)))
262 if (self._wbufsize <= 1 or
263 self._get_wbuf_len() >= self._wbufsize):
264 self.flush()
266 def _get_wbuf_len(self):
267 buf_len = 0
268 for x in self._wbuf:
269 buf_len += len(x)
270 return buf_len
272 def read(self, size=-1):
273 data = self._rbuf
274 if size < 0:
275 # Read until EOF
276 buffers = []
277 if data:
278 buffers.append(data)
279 self._rbuf = ""
280 if self._rbufsize <= 1:
281 recv_size = self.default_bufsize
282 else:
283 recv_size = self._rbufsize
284 while True:
285 data = self._sock.recv(recv_size)
286 if not data:
287 break
288 buffers.append(data)
289 return "".join(buffers)
290 else:
291 # Read until size bytes or EOF seen, whichever comes first
292 buf_len = len(data)
293 if buf_len >= size:
294 self._rbuf = data[size:]
295 return data[:size]
296 buffers = []
297 if data:
298 buffers.append(data)
299 self._rbuf = ""
300 while True:
301 left = size - buf_len
302 recv_size = max(self._rbufsize, left)
303 data = self._sock.recv(recv_size)
304 if not data:
305 break
306 buffers.append(data)
307 n = len(data)
308 if n >= left:
309 self._rbuf = data[left:]
310 buffers[-1] = data[:left]
311 break
312 buf_len += n
313 return "".join(buffers)
315 def readline(self, size=-1):
316 data = self._rbuf
317 if size < 0:
318 # Read until \n or EOF, whichever comes first
319 if self._rbufsize <= 1:
320 # Speed up unbuffered case
321 assert data == ""
322 buffers = []
323 recv = self._sock.recv
324 while data != "\n":
325 data = recv(1)
326 if not data:
327 break
328 buffers.append(data)
329 return "".join(buffers)
330 nl = data.find('\n')
331 if nl >= 0:
332 nl += 1
333 self._rbuf = data[nl:]
334 return data[:nl]
335 buffers = []
336 if data:
337 buffers.append(data)
338 self._rbuf = ""
339 while True:
340 data = self._sock.recv(self._rbufsize)
341 if not data:
342 break
343 buffers.append(data)
344 nl = data.find('\n')
345 if nl >= 0:
346 nl += 1
347 self._rbuf = data[nl:]
348 buffers[-1] = data[:nl]
349 break
350 return "".join(buffers)
351 else:
352 # Read until size bytes or \n or EOF seen, whichever comes first
353 nl = data.find('\n', 0, size)
354 if nl >= 0:
355 nl += 1
356 self._rbuf = data[nl:]
357 return data[:nl]
358 buf_len = len(data)
359 if buf_len >= size:
360 self._rbuf = data[size:]
361 return data[:size]
362 buffers = []
363 if data:
364 buffers.append(data)
365 self._rbuf = ""
366 while True:
367 data = self._sock.recv(self._rbufsize)
368 if not data:
369 break
370 buffers.append(data)
371 left = size - buf_len
372 nl = data.find('\n', 0, left)
373 if nl >= 0:
374 nl += 1
375 self._rbuf = data[nl:]
376 buffers[-1] = data[:nl]
377 break
378 n = len(data)
379 if n >= left:
380 self._rbuf = data[left:]
381 buffers[-1] = data[:left]
382 break
383 buf_len += n
384 return "".join(buffers)
386 def readlines(self, sizehint=0):
387 total = 0
388 list = []
389 while True:
390 line = self.readline()
391 if not line:
392 break
393 list.append(line)
394 total += len(line)
395 if sizehint and total >= sizehint:
396 break
397 return list
399 # Iterator protocols
401 def __iter__(self):
402 return self
404 def next(self):
405 line = self.readline()
406 if not line:
407 raise StopIteration
408 return line