blob: 153f602b26f2cf6f14156cb6c8597307c7c45af5 [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
13fromfd() -- create a socket object from an open file descriptor [*]
14gethostname() -- return the current hostname
15gethostbyname() -- map a hostname to its IP number
16gethostbyaddr() -- map an IP number or hostname to DNS info
17getservbyname() -- map a service name and a protocol name to a port number
18getprotobyname() -- mape a protocol name (e.g. 'tcp') to a number
19ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order
20htons(), htonl() -- convert 16, 32 bit int from host to network byte order
21inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format
22inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89)
23ssl() -- secure socket layer support (only available if configured)
24
25 [*] not available on all platforms!
26
27Special objects:
28
29SocketType -- type object for socket objects
30error -- exception raised for I/O errors
31
32Integer constants:
33
34AF_INET, AF_UNIX -- socket domains (first argument to socket() call)
35SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)
36
37Many other constants may be defined; these may be used in calls to
38the setsockopt() and getsockopt() methods.
39"""
40
Tim Peters18e67782002-02-17 04:25:24 +000041import _socket
Fred Drakea6070f02000-08-16 14:14:32 +000042from _socket import *
Tim Peters18e67782002-02-17 04:25:24 +000043
44SSL_EXISTS = 1
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000045try:
Tim Peters18e67782002-02-17 04:25:24 +000046 import _ssl
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000047 from _ssl import *
48except ImportError:
Tim Peters18e67782002-02-17 04:25:24 +000049 SSL_EXISTS = 0
Fred Drakea6070f02000-08-16 14:14:32 +000050
51import os, sys
52
Skip Montanaro0de65802001-02-15 22:15:14 +000053__all__ = ["getfqdn"]
Skip Montanaro0de65802001-02-15 22:15:14 +000054__all__.extend(os._get_exports_list(_socket))
Tim Peters18e67782002-02-17 04:25:24 +000055# XXX shouldn't there be something similar to the above for _ssl exports?
Skip Montanaro0de65802001-02-15 22:15:14 +000056
Fred Drakea6070f02000-08-16 14:14:32 +000057if (sys.platform.lower().startswith("win")
Guido van Rossumd74fb6b2001-03-02 06:43:49 +000058 or (hasattr(os, 'uname') and os.uname()[0] == "BeOS")
Tim Peters18e67782002-02-17 04:25:24 +000059 or sys.platform=="riscos"):
Fred Drakea6070f02000-08-16 14:14:32 +000060
Guido van Rossum3f69f212001-03-22 22:12:17 +000061 _realsocketcall = _socket.socket
Fred Drakea6070f02000-08-16 14:14:32 +000062
63 def socket(family, type, proto=0):
64 return _socketobject(_realsocketcall(family, type, proto))
65
Tim Peters18e67782002-02-17 04:25:24 +000066 if SSL_EXISTS:
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000067 _realsslcall = _ssl.ssl
Guido van Rossum3f69f212001-03-22 22:12:17 +000068 def ssl(sock, keyfile=None, certfile=None):
69 if hasattr(sock, "_sock"):
70 sock = sock._sock
Tim Petersa19a1682001-03-29 04:36:09 +000071 return _realsslcall(sock, keyfile, certfile)
Guido van Rossum3f69f212001-03-22 22:12:17 +000072
Tim Peters18e67782002-02-17 04:25:24 +000073del _socket
74if SSL_EXISTS:
75 del _ssl
76del SSL_EXISTS
Fred Drakea6070f02000-08-16 14:14:32 +000077
78# WSA error codes
79if sys.platform.lower().startswith("win"):
80 errorTab = {}
81 errorTab[10004] = "The operation was interrupted."
82 errorTab[10009] = "A bad file handle was passed."
83 errorTab[10013] = "Permission denied."
84 errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT
85 errorTab[10022] = "An invalid operation was attempted."
86 errorTab[10035] = "The socket operation would block"
87 errorTab[10036] = "A blocking operation is already in progress."
88 errorTab[10048] = "The network address is in use."
89 errorTab[10054] = "The connection has been reset."
90 errorTab[10058] = "The network has been shut down."
91 errorTab[10060] = "The operation timed out."
92 errorTab[10061] = "Connection refused."
93 errorTab[10063] = "The name is too long."
94 errorTab[10064] = "The host is down."
95 errorTab[10065] = "The host is unreachable."
Skip Montanaro64de1a42001-03-18 19:53:21 +000096 __all__.append("errorTab")
Fred Drakea6070f02000-08-16 14:14:32 +000097del os, sys
98
99
100def getfqdn(name=''):
101 """Get fully qualified domain name from name.
102
103 An empty argument is interpreted as meaning the local host.
104
105 First the hostname returned by gethostbyaddr() is checked, then
106 possibly existing aliases. In case no FQDN is available, hostname
107 is returned.
108 """
109 name = name.strip()
Peter Schneider-Kamp2d2785a2000-08-16 20:30:21 +0000110 if not name or name == '0.0.0.0':
Fred Drakea6070f02000-08-16 14:14:32 +0000111 name = gethostname()
112 try:
113 hostname, aliases, ipaddrs = gethostbyaddr(name)
114 except error:
115 pass
116 else:
117 aliases.insert(0, hostname)
118 for name in aliases:
119 if '.' in name:
120 break
121 else:
122 name = hostname
123 return name
124
125
126#
127# These classes are used by the socket() defined on Windows and BeOS
128# platforms to provide a best-effort implementation of the cleanup
129# semantics needed when sockets can't be dup()ed.
130#
131# These are not actually used on other platforms.
132#
133
Guido van Rossume5e50592001-08-18 01:23:20 +0000134_socketmethods = (
135 'bind', 'connect', 'connect_ex', 'fileno', 'listen',
136 'getpeername', 'getsockname', 'getsockopt', 'setsockopt',
Guido van Rossumb2c763f2001-10-29 07:13:53 +0000137 'recv', 'recvfrom', 'send', 'sendall', 'sendto', 'setblocking', 'shutdown')
Guido van Rossume5e50592001-08-18 01:23:20 +0000138
Fred Drakea6070f02000-08-16 14:14:32 +0000139class _socketobject:
140
Guido van Rossum99d2fbb2001-12-18 22:22:25 +0000141 class _closedsocket:
142 def __getattr__(self, name):
143 raise error(9, 'Bad file descriptor')
144
Fred Drakea6070f02000-08-16 14:14:32 +0000145 def __init__(self, sock):
146 self._sock = sock
147
148 def close(self):
Guido van Rossum99d2fbb2001-12-18 22:22:25 +0000149 # Avoid referencing globals here
150 self._sock = self.__class__._closedsocket()
Fred Drakea6070f02000-08-16 14:14:32 +0000151
152 def __del__(self):
153 self.close()
154
155 def accept(self):
156 sock, addr = self._sock.accept()
157 return _socketobject(sock), addr
158
159 def dup(self):
160 return _socketobject(self._sock)
161
162 def makefile(self, mode='r', bufsize=-1):
163 return _fileobject(self._sock, mode, bufsize)
164
Guido van Rossume5e50592001-08-18 01:23:20 +0000165 _s = "def %s(self, *args): return self._sock.%s(*args)\n\n"
166 for _m in _socketmethods:
Fred Drakea6070f02000-08-16 14:14:32 +0000167 exec _s % (_m, _m)
168
169
170class _fileobject:
171
172 def __init__(self, sock, mode, bufsize):
173 self._sock = sock
174 self._mode = mode
175 if bufsize < 0:
176 bufsize = 512
177 self._rbufsize = max(1, bufsize)
178 self._wbufsize = bufsize
179 self._wbuf = self._rbuf = ""
180
181 def close(self):
182 try:
183 if self._sock:
184 self.flush()
185 finally:
186 self._sock = 0
187
188 def __del__(self):
189 self.close()
190
191 def flush(self):
192 if self._wbuf:
Martin v. Löwise12454f2002-02-16 23:06:19 +0000193 self._sock.sendall(self._wbuf)
Fred Drakea6070f02000-08-16 14:14:32 +0000194 self._wbuf = ""
195
196 def fileno(self):
197 return self._sock.fileno()
198
199 def write(self, data):
200 self._wbuf = self._wbuf + data
201 if self._wbufsize == 1:
202 if '\n' in data:
203 self.flush()
204 else:
205 if len(self._wbuf) >= self._wbufsize:
206 self.flush()
207
208 def writelines(self, list):
Martin v. Löwise12454f2002-02-16 23:06:19 +0000209 filter(self._sock.sendall, list)
Fred Drakea6070f02000-08-16 14:14:32 +0000210 self.flush()
211
212 def read(self, n=-1):
213 if n >= 0:
214 k = len(self._rbuf)
215 if n <= k:
216 data = self._rbuf[:n]
217 self._rbuf = self._rbuf[n:]
218 return data
219 n = n - k
220 L = [self._rbuf]
221 self._rbuf = ""
222 while n > 0:
223 new = self._sock.recv(max(n, self._rbufsize))
224 if not new: break
225 k = len(new)
226 if k > n:
227 L.append(new[:n])
228 self._rbuf = new[n:]
229 break
230 L.append(new)
231 n = n - k
232 return "".join(L)
233 k = max(512, self._rbufsize)
234 L = [self._rbuf]
235 self._rbuf = ""
236 while 1:
237 new = self._sock.recv(k)
238 if not new: break
239 L.append(new)
240 k = min(k*2, 1024**2)
241 return "".join(L)
242
243 def readline(self, limit=-1):
244 data = ""
245 i = self._rbuf.find('\n')
246 while i < 0 and not (0 < limit <= len(self._rbuf)):
247 new = self._sock.recv(self._rbufsize)
248 if not new: break
249 i = new.find('\n')
250 if i >= 0: i = i + len(self._rbuf)
251 self._rbuf = self._rbuf + new
252 if i < 0: i = len(self._rbuf)
253 else: i = i+1
254 if 0 <= limit < len(self._rbuf): i = limit
255 data, self._rbuf = self._rbuf[:i], self._rbuf[i:]
256 return data
257
Martin v. Löwis6df27f82000-09-19 11:25:58 +0000258 def readlines(self, sizehint = 0):
259 total = 0
Fred Drakea6070f02000-08-16 14:14:32 +0000260 list = []
261 while 1:
262 line = self.readline()
263 if not line: break
264 list.append(line)
Martin v. Löwis6df27f82000-09-19 11:25:58 +0000265 total += len(line)
266 if sizehint and total >= sizehint:
267 break
Fred Drakea6070f02000-08-16 14:14:32 +0000268 return list