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