blob: d0f09111a9e6a35b3aab6bf3e08d2f3a5dbb9936 [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
41from _socket import *
42
43import os, sys
44
Skip Montanaro0de65802001-02-15 22:15:14 +000045__all__ = ["getfqdn"]
46import _socket
47__all__.extend(os._get_exports_list(_socket))
Skip Montanaro0de65802001-02-15 22:15:14 +000048
Fred Drakea6070f02000-08-16 14:14:32 +000049if (sys.platform.lower().startswith("win")
Guido van Rossumd74fb6b2001-03-02 06:43:49 +000050 or (hasattr(os, 'uname') and os.uname()[0] == "BeOS")
51 or (sys.platform=="RISCOS")):
Fred Drakea6070f02000-08-16 14:14:32 +000052
Guido van Rossum3f69f212001-03-22 22:12:17 +000053 _realsocketcall = _socket.socket
Fred Drakea6070f02000-08-16 14:14:32 +000054
55 def socket(family, type, proto=0):
56 return _socketobject(_realsocketcall(family, type, proto))
57
Guido van Rossum3f69f212001-03-22 22:12:17 +000058 try:
59 _realsslcall = _socket.ssl
60 except AttributeError:
61 pass # No ssl
62 else:
63 def ssl(sock, keyfile=None, certfile=None):
64 if hasattr(sock, "_sock"):
65 sock = sock._sock
Tim Petersa19a1682001-03-29 04:36:09 +000066 return _realsslcall(sock, keyfile, certfile)
Guido van Rossum3f69f212001-03-22 22:12:17 +000067
Fred Drakea6070f02000-08-16 14:14:32 +000068
69# WSA error codes
70if sys.platform.lower().startswith("win"):
71 errorTab = {}
72 errorTab[10004] = "The operation was interrupted."
73 errorTab[10009] = "A bad file handle was passed."
74 errorTab[10013] = "Permission denied."
75 errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT
76 errorTab[10022] = "An invalid operation was attempted."
77 errorTab[10035] = "The socket operation would block"
78 errorTab[10036] = "A blocking operation is already in progress."
79 errorTab[10048] = "The network address is in use."
80 errorTab[10054] = "The connection has been reset."
81 errorTab[10058] = "The network has been shut down."
82 errorTab[10060] = "The operation timed out."
83 errorTab[10061] = "Connection refused."
84 errorTab[10063] = "The name is too long."
85 errorTab[10064] = "The host is down."
86 errorTab[10065] = "The host is unreachable."
Skip Montanaro64de1a42001-03-18 19:53:21 +000087 __all__.append("errorTab")
Fred Drakea6070f02000-08-16 14:14:32 +000088del os, sys
89
90
91def getfqdn(name=''):
92 """Get fully qualified domain name from name.
93
94 An empty argument is interpreted as meaning the local host.
95
96 First the hostname returned by gethostbyaddr() is checked, then
97 possibly existing aliases. In case no FQDN is available, hostname
98 is returned.
99 """
100 name = name.strip()
Peter Schneider-Kamp2d2785a2000-08-16 20:30:21 +0000101 if not name or name == '0.0.0.0':
Fred Drakea6070f02000-08-16 14:14:32 +0000102 name = gethostname()
103 try:
104 hostname, aliases, ipaddrs = gethostbyaddr(name)
105 except error:
106 pass
107 else:
108 aliases.insert(0, hostname)
109 for name in aliases:
110 if '.' in name:
111 break
112 else:
113 name = hostname
114 return name
115
116
117#
118# These classes are used by the socket() defined on Windows and BeOS
119# platforms to provide a best-effort implementation of the cleanup
120# semantics needed when sockets can't be dup()ed.
121#
122# These are not actually used on other platforms.
123#
124
125class _socketobject:
126
127 def __init__(self, sock):
128 self._sock = sock
129
130 def close(self):
131 self._sock = 0
132
133 def __del__(self):
134 self.close()
135
136 def accept(self):
137 sock, addr = self._sock.accept()
138 return _socketobject(sock), addr
139
140 def dup(self):
141 return _socketobject(self._sock)
142
143 def makefile(self, mode='r', bufsize=-1):
144 return _fileobject(self._sock, mode, bufsize)
145
146 _s = "def %s(self, *args): return apply(self._sock.%s, args)\n\n"
147 for _m in ('bind', 'connect', 'connect_ex', 'fileno', 'listen',
148 'getpeername', 'getsockname',
149 'getsockopt', 'setsockopt',
150 'recv', 'recvfrom', 'send', 'sendto',
151 'setblocking',
152 'shutdown'):
153 exec _s % (_m, _m)
154
155
156class _fileobject:
157
158 def __init__(self, sock, mode, bufsize):
159 self._sock = sock
160 self._mode = mode
161 if bufsize < 0:
162 bufsize = 512
163 self._rbufsize = max(1, bufsize)
164 self._wbufsize = bufsize
165 self._wbuf = self._rbuf = ""
166
167 def close(self):
168 try:
169 if self._sock:
170 self.flush()
171 finally:
172 self._sock = 0
173
174 def __del__(self):
175 self.close()
176
177 def flush(self):
178 if self._wbuf:
179 self._sock.send(self._wbuf)
180 self._wbuf = ""
181
182 def fileno(self):
183 return self._sock.fileno()
184
185 def write(self, data):
186 self._wbuf = self._wbuf + data
187 if self._wbufsize == 1:
188 if '\n' in data:
189 self.flush()
190 else:
191 if len(self._wbuf) >= self._wbufsize:
192 self.flush()
193
194 def writelines(self, list):
195 filter(self._sock.send, list)
196 self.flush()
197
198 def read(self, n=-1):
199 if n >= 0:
200 k = len(self._rbuf)
201 if n <= k:
202 data = self._rbuf[:n]
203 self._rbuf = self._rbuf[n:]
204 return data
205 n = n - k
206 L = [self._rbuf]
207 self._rbuf = ""
208 while n > 0:
209 new = self._sock.recv(max(n, self._rbufsize))
210 if not new: break
211 k = len(new)
212 if k > n:
213 L.append(new[:n])
214 self._rbuf = new[n:]
215 break
216 L.append(new)
217 n = n - k
218 return "".join(L)
219 k = max(512, self._rbufsize)
220 L = [self._rbuf]
221 self._rbuf = ""
222 while 1:
223 new = self._sock.recv(k)
224 if not new: break
225 L.append(new)
226 k = min(k*2, 1024**2)
227 return "".join(L)
228
229 def readline(self, limit=-1):
230 data = ""
231 i = self._rbuf.find('\n')
232 while i < 0 and not (0 < limit <= len(self._rbuf)):
233 new = self._sock.recv(self._rbufsize)
234 if not new: break
235 i = new.find('\n')
236 if i >= 0: i = i + len(self._rbuf)
237 self._rbuf = self._rbuf + new
238 if i < 0: i = len(self._rbuf)
239 else: i = i+1
240 if 0 <= limit < len(self._rbuf): i = limit
241 data, self._rbuf = self._rbuf[:i], self._rbuf[i:]
242 return data
243
Martin v. Löwis6df27f82000-09-19 11:25:58 +0000244 def readlines(self, sizehint = 0):
245 total = 0
Fred Drakea6070f02000-08-16 14:14:32 +0000246 list = []
247 while 1:
248 line = self.readline()
249 if not line: break
250 list.append(line)
Martin v. Löwis6df27f82000-09-19 11:25:58 +0000251 total += len(line)
252 if sizehint and total >= sizehint:
253 break
Fred Drakea6070f02000-08-16 14:14:32 +0000254 return list