blob: f96a14683715eabfec8936cea14e6f9a63a381cb [file] [log] [blame]
Fred Drakea6070f02000-08-16 14:14:32 +00001# Wrapper module for _socket, providing some additional facilities
2# implemented in Python.
3
4"""\
5This module provides socket operations and some related functions.
6On Unix, it supports IP (Internet Protocol) and Unix domain sockets.
Tim Peters495ad3c2001-01-15 01:36:40 +00007On other systems, it only supports IP. Functions specific for a
Martin v. Löwisaf484d52000-09-30 11:34:30 +00008socket are available as methods of the socket object.
Fred Drakea6070f02000-08-16 14:14:32 +00009
10Functions:
11
12socket() -- create a new socket object
Dave Cole331708b2004-08-09 04:51:41 +000013socketpair() -- create a pair of new socket objects [*]
Fred Drakea6070f02000-08-16 14:14:32 +000014fromfd() -- create a socket object from an open file descriptor [*]
15gethostname() -- return the current hostname
16gethostbyname() -- map a hostname to its IP number
17gethostbyaddr() -- map an IP number or hostname to DNS info
18getservbyname() -- map a service name and a protocol name to a port number
19getprotobyname() -- mape a protocol name (e.g. 'tcp') to a number
20ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order
21htons(), htonl() -- convert 16, 32 bit int from host to network byte order
22inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format
23inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89)
24ssl() -- secure socket layer support (only available if configured)
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +000025socket.getdefaulttimeout() -- get the default timeout value
26socket.setdefaulttimeout() -- set the default timeout value
Fred Drakea6070f02000-08-16 14:14:32 +000027
28 [*] not available on all platforms!
29
30Special objects:
31
32SocketType -- type object for socket objects
33error -- exception raised for I/O errors
Guido van Rossum47dfa4a2003-04-25 05:48:32 +000034has_ipv6 -- boolean value indicating if IPv6 is supported
Fred Drakea6070f02000-08-16 14:14:32 +000035
36Integer constants:
37
38AF_INET, AF_UNIX -- socket domains (first argument to socket() call)
39SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)
40
41Many other constants may be defined; these may be used in calls to
42the setsockopt() and getsockopt() methods.
43"""
44
Tim Peters18e67782002-02-17 04:25:24 +000045import _socket
Fred Drakea6070f02000-08-16 14:14:32 +000046from _socket import *
Tim Peters18e67782002-02-17 04:25:24 +000047
Guido van Rossumc18993f2002-08-08 15:16:20 +000048_have_ssl = False
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000049try:
Guido van Rossumde7cade2002-08-08 15:25:28 +000050 import _ssl
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000051 from _ssl import *
Guido van Rossumc18993f2002-08-08 15:16:20 +000052 _have_ssl = True
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000053except ImportError:
Guido van Rossumc18993f2002-08-08 15:16:20 +000054 pass
Fred Drakea6070f02000-08-16 14:14:32 +000055
56import os, sys
57
Fred Drake70d566b2003-04-29 19:50:25 +000058try:
59 from errno import EBADF
60except ImportError:
61 EBADF = 9
62
Skip Montanaro0de65802001-02-15 22:15:14 +000063__all__ = ["getfqdn"]
Skip Montanaro0de65802001-02-15 22:15:14 +000064__all__.extend(os._get_exports_list(_socket))
Guido van Rossumde7cade2002-08-08 15:25:28 +000065if _have_ssl:
66 __all__.extend(os._get_exports_list(_ssl))
Skip Montanaro0de65802001-02-15 22:15:14 +000067
Guido van Rossumc18993f2002-08-08 15:16:20 +000068_realsocket = socket
Martin v. Löwis1867f242003-06-14 13:30:53 +000069if _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)
Fred Drakea6070f02000-08-16 14:14:32 +000075
76# WSA error codes
77if 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."
Skip Montanaro64de1a42001-03-18 19:53:21 +000094 __all__.append("errorTab")
Guido van Rossumde7cade2002-08-08 15:25:28 +000095
Fred Drakea6070f02000-08-16 14:14:32 +000096
97
98def getfqdn(name=''):
99 """Get fully qualified domain name from name.
100
101 An empty argument is interpreted as meaning the local host.
102
103 First the hostname returned by gethostbyaddr() is checked, then
104 possibly existing aliases. In case no FQDN is available, hostname
105 is returned.
106 """
107 name = name.strip()
Peter Schneider-Kamp2d2785a2000-08-16 20:30:21 +0000108 if not name or name == '0.0.0.0':
Fred Drakea6070f02000-08-16 14:14:32 +0000109 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
122
123
124#
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.
128#
129# These are not actually used on other platforms.
130#
131
Guido van Rossume5e50592001-08-18 01:23:20 +0000132_socketmethods = (
133 'bind', 'connect', 'connect_ex', 'fileno', 'listen',
134 'getpeername', 'getsockname', 'getsockopt', 'setsockopt',
Skip Montanaroc6899182003-04-29 19:27:26 +0000135 'sendall', 'setblocking',
Guido van Rossum67f7a382002-06-06 21:08:16 +0000136 'settimeout', 'gettimeout', 'shutdown')
Guido van Rossume5e50592001-08-18 01:23:20 +0000137
Martin v. Löwisa94568a2003-05-10 07:36:56 +0000138if sys.platform == "riscos":
139 _socketmethods = _socketmethods + ('sleeptaskw',)
140
Guido van Rossum715f9702002-08-08 18:11:36 +0000141class _closedsocket(object):
142 __slots__ = []
Skip Montanaroc6899182003-04-29 19:27:26 +0000143 def _dummy(*args):
Fred Drake70d566b2003-04-29 19:50:25 +0000144 raise error(EBADF, 'Bad file descriptor')
Skip Montanaroc6899182003-04-29 19:27:26 +0000145 send = recv = sendto = recvfrom = __getattr__ = _dummy
Guido van Rossum715f9702002-08-08 18:11:36 +0000146
Guido van Rossumc18993f2002-08-08 15:16:20 +0000147class _socketobject(object):
Fred Drakea6070f02000-08-16 14:14:32 +0000148
Guido van Rossumc18993f2002-08-08 15:16:20 +0000149 __doc__ = _realsocket.__doc__
150
Raymond Hettinger027bb632004-05-31 03:09:25 +0000151 __slots__ = ["_sock", "send", "recv", "sendto", "recvfrom",
152 "__weakref__"]
Guido van Rossumc18993f2002-08-08 15:16:20 +0000153
Guido van Rossumc18993f2002-08-08 15:16:20 +0000154 def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None):
155 if _sock is None:
Guido van Rossum7c3b6342002-08-08 15:22:12 +0000156 _sock = _realsocket(family, type, proto)
Guido van Rossumc18993f2002-08-08 15:16:20 +0000157 self._sock = _sock
Skip Montanaroc6899182003-04-29 19:27:26 +0000158 self.send = self._sock.send
159 self.recv = self._sock.recv
160 self.sendto = self._sock.sendto
161 self.recvfrom = self._sock.recvfrom
Fred Drakea6070f02000-08-16 14:14:32 +0000162
163 def close(self):
Guido van Rossum715f9702002-08-08 18:11:36 +0000164 self._sock = _closedsocket()
Skip Montanaroc6899182003-04-29 19:27:26 +0000165 self.send = self.recv = self.sendto = self.recvfrom = self._sock._dummy
Guido van Rossumc18993f2002-08-08 15:16:20 +0000166 close.__doc__ = _realsocket.close.__doc__
Fred Drakea6070f02000-08-16 14:14:32 +0000167
Fred Drakea6070f02000-08-16 14:14:32 +0000168 def accept(self):
169 sock, addr = self._sock.accept()
Guido van Rossumc18993f2002-08-08 15:16:20 +0000170 return _socketobject(_sock=sock), addr
171 accept.__doc__ = _realsocket.accept.__doc__
Fred Drakea6070f02000-08-16 14:14:32 +0000172
173 def dup(self):
Guido van Rossumc18993f2002-08-08 15:16:20 +0000174 """dup() -> socket object
175
176 Return a new socket object connected to the same system resource."""
177 return _socketobject(_sock=self._sock)
Fred Drakea6070f02000-08-16 14:14:32 +0000178
179 def makefile(self, mode='r', bufsize=-1):
Guido van Rossumc18993f2002-08-08 15:16:20 +0000180 """makefile([mode[, bufsize]]) -> file object
181
182 Return a regular file object corresponding to the socket. The mode
183 and bufsize arguments are as for the built-in open() function."""
Fred Drakea6070f02000-08-16 14:14:32 +0000184 return _fileobject(self._sock, mode, bufsize)
185
Guido van Rossumc18993f2002-08-08 15:16:20 +0000186 _s = ("def %s(self, *args): return self._sock.%s(*args)\n\n"
187 "%s.__doc__ = _realsocket.%s.__doc__\n")
Guido van Rossume5e50592001-08-18 01:23:20 +0000188 for _m in _socketmethods:
Guido van Rossumc18993f2002-08-08 15:16:20 +0000189 exec _s % (_m, _m, _m, _m)
Tim Petersd7e8a0d2002-08-08 20:07:03 +0000190 del _m, _s
Fred Drakea6070f02000-08-16 14:14:32 +0000191
Skip Montanaro89feabc2003-03-30 04:54:24 +0000192socket = SocketType = _socketobject
Fred Drakea6070f02000-08-16 14:14:32 +0000193
Guido van Rossumc18993f2002-08-08 15:16:20 +0000194class _fileobject(object):
Guido van Rossum443fec32002-08-08 01:02:16 +0000195 """Faux file object attached to a socket object."""
196
197 default_bufsize = 8192
Guido van Rossumc18993f2002-08-08 15:16:20 +0000198 name = "<socket>"
199
200 __slots__ = ["mode", "bufsize", "softspace",
201 # "closed" is a property, see below
202 "_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf"]
Fred Drakea6070f02000-08-16 14:14:32 +0000203
Guido van Rossume9f66142002-08-07 15:46:19 +0000204 def __init__(self, sock, mode='rb', bufsize=-1):
Fred Drakea6070f02000-08-16 14:14:32 +0000205 self._sock = sock
Guido van Rossumc18993f2002-08-08 15:16:20 +0000206 self.mode = mode # Not actually used in this version
Guido van Rossum443fec32002-08-08 01:02:16 +0000207 if bufsize < 0:
208 bufsize = self.default_bufsize
Guido van Rossum7c3b6342002-08-08 15:22:12 +0000209 self.bufsize = bufsize
210 self.softspace = False
Guido van Rossum443fec32002-08-08 01:02:16 +0000211 if bufsize == 0:
212 self._rbufsize = 1
213 elif bufsize == 1:
214 self._rbufsize = self.default_bufsize
215 else:
216 self._rbufsize = bufsize
Fred Drakea6070f02000-08-16 14:14:32 +0000217 self._wbufsize = bufsize
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000218 self._rbuf = "" # A string
219 self._wbuf = [] # A list of strings
Fred Drakea6070f02000-08-16 14:14:32 +0000220
Guido van Rossumc18993f2002-08-08 15:16:20 +0000221 def _getclosed(self):
Tim Peters116d83c2004-03-28 02:20:45 +0000222 return self._sock is None
Guido van Rossumc18993f2002-08-08 15:16:20 +0000223 closed = property(_getclosed, doc="True if the file is closed")
224
Fred Drakea6070f02000-08-16 14:14:32 +0000225 def close(self):
226 try:
227 if self._sock:
228 self.flush()
229 finally:
Guido van Rossum67f7a382002-06-06 21:08:16 +0000230 self._sock = None
Fred Drakea6070f02000-08-16 14:14:32 +0000231
232 def __del__(self):
Guido van Rossum65f8ced2003-05-29 14:36:57 +0000233 try:
234 self.close()
235 except:
236 # close() may fail if __init__ didn't complete
237 pass
Fred Drakea6070f02000-08-16 14:14:32 +0000238
239 def flush(self):
240 if self._wbuf:
Guido van Rossum443fec32002-08-08 01:02:16 +0000241 buffer = "".join(self._wbuf)
242 self._wbuf = []
Guido van Rossum67f7a382002-06-06 21:08:16 +0000243 self._sock.sendall(buffer)
Fred Drakea6070f02000-08-16 14:14:32 +0000244
Neal Norwitz2b342902002-06-13 22:18:39 +0000245 def fileno(self):
Fred Drakea6070f02000-08-16 14:14:32 +0000246 return self._sock.fileno()
247
248 def write(self, data):
Guido van Rossum443fec32002-08-08 01:02:16 +0000249 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):
Guido van Rossum67f7a382002-06-06 21:08:16 +0000256 self.flush()
Fred Drakea6070f02000-08-16 14:14:32 +0000257
258 def writelines(self, list):
Guido van Rossum443fec32002-08-08 01:02:16 +0000259 # 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()
Fred Drakea6070f02000-08-16 14:14:32 +0000265
Guido van Rossum443fec32002-08-08 01:02:16 +0000266 def _get_wbuf_len(self):
Guido van Rossum67f7a382002-06-06 21:08:16 +0000267 buf_len = 0
Guido van Rossum443fec32002-08-08 01:02:16 +0000268 for x in self._wbuf:
269 buf_len += len(x)
Guido van Rossum67f7a382002-06-06 21:08:16 +0000270 return buf_len
Fred Drakea6070f02000-08-16 14:14:32 +0000271
Guido van Rossum67f7a382002-06-06 21:08:16 +0000272 def read(self, size=-1):
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000273 data = self._rbuf
Guido van Rossum443fec32002-08-08 01:02:16 +0000274 if size < 0:
275 # Read until EOF
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000276 buffers = []
277 if data:
278 buffers.append(data)
279 self._rbuf = ""
Guido van Rossum443fec32002-08-08 01:02:16 +0000280 if self._rbufsize <= 1:
281 recv_size = self.default_bufsize
282 else:
283 recv_size = self._rbufsize
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000284 while True:
Guido van Rossum443fec32002-08-08 01:02:16 +0000285 data = self._sock.recv(recv_size)
286 if not data:
287 break
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000288 buffers.append(data)
289 return "".join(buffers)
Guido van Rossum443fec32002-08-08 01:02:16 +0000290 else:
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000291 # 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)
Guido van Rossum443fec32002-08-08 01:02:16 +0000303 data = self._sock.recv(recv_size)
304 if not data:
305 break
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000306 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)
Fred Drakea6070f02000-08-16 14:14:32 +0000314
Guido van Rossum67f7a382002-06-06 21:08:16 +0000315 def readline(self, size=-1):
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000316 data = self._rbuf
317 if size < 0:
318 # Read until \n or EOF, whichever comes first
Guido van Rossum48b79692002-08-08 17:34:19 +0000319 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)
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000330 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)
Guido van Rossum67f7a382002-06-06 21:08:16 +0000351 else:
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000352 # 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)
Guido van Rossum67f7a382002-06-06 21:08:16 +0000385
386 def readlines(self, sizehint=0):
Martin v. Löwis6df27f82000-09-19 11:25:58 +0000387 total = 0
Fred Drakea6070f02000-08-16 14:14:32 +0000388 list = []
Guido van Rossumfb3deec2002-08-08 17:16:09 +0000389 while True:
Fred Drakea6070f02000-08-16 14:14:32 +0000390 line = self.readline()
Neal Norwitz2b342902002-06-13 22:18:39 +0000391 if not line:
392 break
Fred Drakea6070f02000-08-16 14:14:32 +0000393 list.append(line)
Martin v. Löwis6df27f82000-09-19 11:25:58 +0000394 total += len(line)
395 if sizehint and total >= sizehint:
396 break
Fred Drakea6070f02000-08-16 14:14:32 +0000397 return list
Guido van Rossum443fec32002-08-08 01:02:16 +0000398
399 # Iterator protocols
400
401 def __iter__(self):
402 return self
403
404 def next(self):
405 line = self.readline()
406 if not line:
407 raise StopIteration
408 return line