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