blob: 136a052e369accaf69cab3cf43a305192b785d4f [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."
82del os, sys
83
84
85def getfqdn(name=''):
86 """Get fully qualified domain name from name.
87
88 An empty argument is interpreted as meaning the local host.
89
90 First the hostname returned by gethostbyaddr() is checked, then
91 possibly existing aliases. In case no FQDN is available, hostname
92 is returned.
93 """
94 name = name.strip()
Peter Schneider-Kamp2d2785a2000-08-16 20:30:21 +000095 if not name or name == '0.0.0.0':
Fred Drakea6070f02000-08-16 14:14:32 +000096 name = gethostname()
97 try:
98 hostname, aliases, ipaddrs = gethostbyaddr(name)
99 except error:
100 pass
101 else:
102 aliases.insert(0, hostname)
103 for name in aliases:
104 if '.' in name:
105 break
106 else:
107 name = hostname
108 return name
109
110
111#
112# These classes are used by the socket() defined on Windows and BeOS
113# platforms to provide a best-effort implementation of the cleanup
114# semantics needed when sockets can't be dup()ed.
115#
116# These are not actually used on other platforms.
117#
118
119class _socketobject:
120
121 def __init__(self, sock):
122 self._sock = sock
123
124 def close(self):
125 self._sock = 0
126
127 def __del__(self):
128 self.close()
129
130 def accept(self):
131 sock, addr = self._sock.accept()
132 return _socketobject(sock), addr
133
134 def dup(self):
135 return _socketobject(self._sock)
136
137 def makefile(self, mode='r', bufsize=-1):
138 return _fileobject(self._sock, mode, bufsize)
139
140 _s = "def %s(self, *args): return apply(self._sock.%s, args)\n\n"
141 for _m in ('bind', 'connect', 'connect_ex', 'fileno', 'listen',
142 'getpeername', 'getsockname',
143 'getsockopt', 'setsockopt',
144 'recv', 'recvfrom', 'send', 'sendto',
145 'setblocking',
146 'shutdown'):
147 exec _s % (_m, _m)
148
149
150class _fileobject:
151
152 def __init__(self, sock, mode, bufsize):
153 self._sock = sock
154 self._mode = mode
155 if bufsize < 0:
156 bufsize = 512
157 self._rbufsize = max(1, bufsize)
158 self._wbufsize = bufsize
159 self._wbuf = self._rbuf = ""
160
161 def close(self):
162 try:
163 if self._sock:
164 self.flush()
165 finally:
166 self._sock = 0
167
168 def __del__(self):
169 self.close()
170
171 def flush(self):
172 if self._wbuf:
173 self._sock.send(self._wbuf)
174 self._wbuf = ""
175
176 def fileno(self):
177 return self._sock.fileno()
178
179 def write(self, data):
180 self._wbuf = self._wbuf + data
181 if self._wbufsize == 1:
182 if '\n' in data:
183 self.flush()
184 else:
185 if len(self._wbuf) >= self._wbufsize:
186 self.flush()
187
188 def writelines(self, list):
189 filter(self._sock.send, list)
190 self.flush()
191
192 def read(self, n=-1):
193 if n >= 0:
194 k = len(self._rbuf)
195 if n <= k:
196 data = self._rbuf[:n]
197 self._rbuf = self._rbuf[n:]
198 return data
199 n = n - k
200 L = [self._rbuf]
201 self._rbuf = ""
202 while n > 0:
203 new = self._sock.recv(max(n, self._rbufsize))
204 if not new: break
205 k = len(new)
206 if k > n:
207 L.append(new[:n])
208 self._rbuf = new[n:]
209 break
210 L.append(new)
211 n = n - k
212 return "".join(L)
213 k = max(512, self._rbufsize)
214 L = [self._rbuf]
215 self._rbuf = ""
216 while 1:
217 new = self._sock.recv(k)
218 if not new: break
219 L.append(new)
220 k = min(k*2, 1024**2)
221 return "".join(L)
222
223 def readline(self, limit=-1):
224 data = ""
225 i = self._rbuf.find('\n')
226 while i < 0 and not (0 < limit <= len(self._rbuf)):
227 new = self._sock.recv(self._rbufsize)
228 if not new: break
229 i = new.find('\n')
230 if i >= 0: i = i + len(self._rbuf)
231 self._rbuf = self._rbuf + new
232 if i < 0: i = len(self._rbuf)
233 else: i = i+1
234 if 0 <= limit < len(self._rbuf): i = limit
235 data, self._rbuf = self._rbuf[:i], self._rbuf[i:]
236 return data
237
Martin v. Löwis6df27f82000-09-19 11:25:58 +0000238 def readlines(self, sizehint = 0):
239 total = 0
Fred Drakea6070f02000-08-16 14:14:32 +0000240 list = []
241 while 1:
242 line = self.readline()
243 if not line: break
244 list.append(line)
Martin v. Löwis6df27f82000-09-19 11:25:58 +0000245 total += len(line)
246 if sizehint and total >= sizehint:
247 break
Fred Drakea6070f02000-08-16 14:14:32 +0000248 return list