Merged revisions 83951 via svnmerge from
[python/dscho.git] / Lib / socket.py
blobbe019dbc51a30998a21c9fda702e6f5f5edc3dc1
1 # Wrapper module for _socket, providing some additional facilities
2 # implemented in Python.
4 """\
5 This module provides socket operations and some related functions.
6 On Unix, it supports IP (Internet Protocol) and Unix domain sockets.
7 On other systems, it only supports IP. Functions specific for a
8 socket are available as methods of the socket object.
10 Functions:
12 socket() -- create a new socket object
13 socketpair() -- create a pair of new socket objects [*]
14 fromfd() -- create a socket object from an open file descriptor [*]
15 gethostname() -- return the current hostname
16 gethostbyname() -- map a hostname to its IP number
17 gethostbyaddr() -- map an IP number or hostname to DNS info
18 getservbyname() -- map a service name and a protocol name to a port number
19 getprotobyname() -- map a protocol name (e.g. 'tcp') to a number
20 ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order
21 htons(), htonl() -- convert 16, 32 bit int from host to network byte order
22 inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format
23 inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89)
24 socket.getdefaulttimeout() -- get the default timeout value
25 socket.setdefaulttimeout() -- set the default timeout value
26 create_connection() -- connects to an address, with an optional timeout
28 [*] not available on all platforms!
30 Special objects:
32 SocketType -- type object for socket objects
33 error -- exception raised for I/O errors
34 has_ipv6 -- boolean value indicating if IPv6 is supported
36 Integer constants:
38 AF_INET, AF_UNIX -- socket domains (first argument to socket() call)
39 SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)
41 Many other constants may be defined; these may be used in calls to
42 the setsockopt() and getsockopt() methods.
43 """
45 import _socket
46 from _socket import *
48 import os, sys, io
50 try:
51 from errno import EBADF
52 except ImportError:
53 EBADF = 9
55 __all__ = ["getfqdn", "create_connection"]
56 __all__.extend(os._get_exports_list(_socket))
59 _realsocket = socket
61 # WSA error codes
62 if sys.platform.lower().startswith("win"):
63 errorTab = {}
64 errorTab[10004] = "The operation was interrupted."
65 errorTab[10009] = "A bad file handle was passed."
66 errorTab[10013] = "Permission denied."
67 errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT
68 errorTab[10022] = "An invalid operation was attempted."
69 errorTab[10035] = "The socket operation would block"
70 errorTab[10036] = "A blocking operation is already in progress."
71 errorTab[10048] = "The network address is in use."
72 errorTab[10054] = "The connection has been reset."
73 errorTab[10058] = "The network has been shut down."
74 errorTab[10060] = "The operation timed out."
75 errorTab[10061] = "Connection refused."
76 errorTab[10063] = "The name is too long."
77 errorTab[10064] = "The host is down."
78 errorTab[10065] = "The host is unreachable."
79 __all__.append("errorTab")
82 class socket(_socket.socket):
84 """A subclass of _socket.socket adding the makefile() method."""
86 __slots__ = ["__weakref__", "_io_refs", "_closed"]
88 def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None):
89 _socket.socket.__init__(self, family, type, proto, fileno)
90 self._io_refs = 0
91 self._closed = False
93 def __repr__(self):
94 """Wrap __repr__() to reveal the real class name."""
95 s = _socket.socket.__repr__(self)
96 if s.startswith("<socket object"):
97 s = "<%s.%s%s%s" % (self.__class__.__module__,
98 self.__class__.__name__,
99 (self._closed and " [closed] ") or "",
100 s[7:])
101 return s
103 def dup(self):
104 """dup() -> socket object
106 Return a new socket object connected to the same system resource.
108 fd = dup(self.fileno())
109 sock = self.__class__(self.family, self.type, self.proto, fileno=fd)
110 sock.settimeout(self.gettimeout())
111 return sock
113 def accept(self):
114 """accept() -> (socket object, address info)
116 Wait for an incoming connection. Return a new socket
117 representing the connection, and the address of the client.
118 For IP sockets, the address info is a pair (hostaddr, port).
120 fd, addr = self._accept()
121 return socket(self.family, self.type, self.proto, fileno=fd), addr
123 def makefile(self, mode="r", buffering=None, *,
124 encoding=None, newline=None):
125 """makefile(...) -> an I/O stream connected to the socket
127 The arguments are as for io.open() after the filename,
128 except the only mode characters supported are 'r', 'w' and 'b'.
129 The semantics are similar too. (XXX refactor to share code?)
131 for c in mode:
132 if c not in {"r", "w", "b"}:
133 raise ValueError("invalid mode %r (only r, w, b allowed)")
134 writing = "w" in mode
135 reading = "r" in mode or not writing
136 assert reading or writing
137 binary = "b" in mode
138 rawmode = ""
139 if reading:
140 rawmode += "r"
141 if writing:
142 rawmode += "w"
143 raw = SocketIO(self, rawmode)
144 self._io_refs += 1
145 if buffering is None:
146 buffering = -1
147 if buffering < 0:
148 buffering = io.DEFAULT_BUFFER_SIZE
149 if buffering == 0:
150 if not binary:
151 raise ValueError("unbuffered streams must be binary")
152 return raw
153 if reading and writing:
154 buffer = io.BufferedRWPair(raw, raw, buffering)
155 elif reading:
156 buffer = io.BufferedReader(raw, buffering)
157 else:
158 assert writing
159 buffer = io.BufferedWriter(raw, buffering)
160 if binary:
161 return buffer
162 text = io.TextIOWrapper(buffer, encoding, newline)
163 text.mode = mode
164 return text
166 def _decref_socketios(self):
167 if self._io_refs > 0:
168 self._io_refs -= 1
169 if self._closed:
170 self.close()
172 def _real_close(self):
173 _socket.socket.close(self)
175 def close(self):
176 self._closed = True
177 if self._io_refs <= 0:
178 self._real_close()
180 def fromfd(fd, family, type, proto=0):
181 """ fromfd(fd, family, type[, proto]) -> socket object
183 Create a socket object from a duplicate of the given file
184 descriptor. The remaining arguments are the same as for socket().
186 nfd = dup(fd)
187 return socket(family, type, proto, nfd)
190 class SocketIO(io.RawIOBase):
192 """Raw I/O implementation for stream sockets.
194 This class supports the makefile() method on sockets. It provides
195 the raw I/O interface on top of a socket object.
198 # XXX More docs
200 def __init__(self, sock, mode):
201 if mode not in ("r", "w", "rw", "rb", "wb", "rwb"):
202 raise ValueError("invalid mode: %r" % mode)
203 io.RawIOBase.__init__(self)
204 self._sock = sock
205 if "b" not in mode:
206 mode += "b"
207 self._mode = mode
208 self._reading = "r" in mode
209 self._writing = "w" in mode
211 def readinto(self, b):
212 self._checkClosed()
213 self._checkReadable()
214 return self._sock.recv_into(b)
216 def write(self, b):
217 self._checkClosed()
218 self._checkWritable()
219 return self._sock.send(b)
221 def readable(self):
222 return self._reading and not self.closed
224 def writable(self):
225 return self._writing and not self.closed
227 def fileno(self):
228 self._checkClosed()
229 return self._sock.fileno()
231 @property
232 def name(self):
233 return self.fileno()
235 @property
236 def mode(self):
237 return self._mode
239 def close(self):
240 if self.closed:
241 return
242 io.RawIOBase.close(self)
243 self._sock._decref_socketios()
244 self._sock = None
246 def __del__(self):
247 if not self.closed:
248 self._sock._decref_socketios()
251 def getfqdn(name=''):
252 """Get fully qualified domain name from name.
254 An empty argument is interpreted as meaning the local host.
256 First the hostname returned by gethostbyaddr() is checked, then
257 possibly existing aliases. In case no FQDN is available, hostname
258 from gethostname() is returned.
260 name = name.strip()
261 if not name or name == '0.0.0.0':
262 name = gethostname()
263 try:
264 hostname, aliases, ipaddrs = gethostbyaddr(name)
265 except error:
266 pass
267 else:
268 aliases.insert(0, hostname)
269 for name in aliases:
270 if '.' in name:
271 break
272 else:
273 name = hostname
274 return name
277 _GLOBAL_DEFAULT_TIMEOUT = object()
279 def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT):
280 """Connect to *address* and return the socket object.
282 Convenience function. Connect to *address* (a 2-tuple ``(host,
283 port)``) and return the socket object. Passing the optional
284 *timeout* parameter will set the timeout on the socket instance
285 before attempting to connect. If no *timeout* is supplied, the
286 global default timeout setting returned by :func:`getdefaulttimeout`
287 is used.
290 msg = "getaddrinfo returns an empty list"
291 host, port = address
292 for res in getaddrinfo(host, port, 0, SOCK_STREAM):
293 af, socktype, proto, canonname, sa = res
294 sock = None
295 try:
296 sock = socket(af, socktype, proto)
297 if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
298 sock.settimeout(timeout)
299 sock.connect(sa)
300 return sock
302 except error as err:
303 msg = err
304 if sock is not None:
305 sock.close()
307 raise error(msg)