blob: 8d3508a81fd40f077304b72c3ab7846a7e498533 [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
Dave Cole331708b2004-08-09 04:51:41 +000013socketpair() -- create a pair of new socket objects [*]
Fred Drakea6070f02000-08-16 14:14:32 +000014fromfd() -- create a socket object from an open file descriptor [*]
15gethostname() -- return the current hostname
16gethostbyname() -- map a hostname to its IP number
17gethostbyaddr() -- map an IP number or hostname to DNS info
18getservbyname() -- map a service name and a protocol name to a port number
19getprotobyname() -- mape a protocol name (e.g. 'tcp') to a number
20ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order
21htons(), htonl() -- convert 16, 32 bit int from host to network byte order
22inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format
23inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89)
24ssl() -- secure socket layer support (only available if configured)
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +000025socket.getdefaulttimeout() -- get the default timeout value
26socket.setdefaulttimeout() -- set the default timeout value
Guido van Rossumd8faa362007-04-27 19:54:29 +000027create_connection() -- connects to an address, with an optional timeout
Fred Drakea6070f02000-08-16 14:14:32 +000028
29 [*] not available on all platforms!
30
31Special objects:
32
33SocketType -- type object for socket objects
34error -- exception raised for I/O errors
Guido van Rossum47dfa4a2003-04-25 05:48:32 +000035has_ipv6 -- boolean value indicating if IPv6 is supported
Fred Drakea6070f02000-08-16 14:14:32 +000036
37Integer constants:
38
39AF_INET, AF_UNIX -- socket domains (first argument to socket() call)
40SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)
41
42Many other constants may be defined; these may be used in calls to
43the setsockopt() and getsockopt() methods.
44"""
45
Tim Peters18e67782002-02-17 04:25:24 +000046import _socket
Fred Drakea6070f02000-08-16 14:14:32 +000047from _socket import *
Tim Peters18e67782002-02-17 04:25:24 +000048
Guido van Rossumc18993f2002-08-08 15:16:20 +000049_have_ssl = False
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000050try:
Guido van Rossumde7cade2002-08-08 15:25:28 +000051 import _ssl
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000052 from _ssl import *
Guido van Rossumc18993f2002-08-08 15:16:20 +000053 _have_ssl = True
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000054except ImportError:
Guido van Rossumc18993f2002-08-08 15:16:20 +000055 pass
Fred Drakea6070f02000-08-16 14:14:32 +000056
Guido van Rossum7d0a8262007-05-21 23:13:11 +000057import os, sys, io
Fred Drakea6070f02000-08-16 14:14:32 +000058
Fred Drake70d566b2003-04-29 19:50:25 +000059try:
60 from errno import EBADF
61except ImportError:
62 EBADF = 9
63
Skip Montanaro0de65802001-02-15 22:15:14 +000064__all__ = ["getfqdn"]
Skip Montanaro0de65802001-02-15 22:15:14 +000065__all__.extend(os._get_exports_list(_socket))
Guido van Rossumde7cade2002-08-08 15:25:28 +000066if _have_ssl:
67 __all__.extend(os._get_exports_list(_ssl))
Skip Montanaro0de65802001-02-15 22:15:14 +000068
Fred Drakea6070f02000-08-16 14:14:32 +000069# 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")
Guido van Rossumde7cade2002-08-08 15:25:28 +000088
Fred Drakea6070f02000-08-16 14:14:32 +000089
Guido van Rossum93adc5d2007-07-17 20:41:19 +000090# True if os.dup() can duplicate socket descriptors.
91# (On Windows at least, os.dup only works on files)
92_can_dup_socket = hasattr(_socket, "dup")
93
94if _can_dup_socket:
Guido van Rossum7d0a8262007-05-21 23:13:11 +000095 def fromfd(fd, family=AF_INET, type=SOCK_STREAM, proto=0):
96 nfd = os.dup(fd)
97 return socket(family, type, proto, fileno=nfd)
98
99
100class socket(_socket.socket):
101
102 """A subclass of _socket.socket adding the makefile() method."""
103
104 __slots__ = ["__weakref__"]
Guido van Rossum93adc5d2007-07-17 20:41:19 +0000105 if not _can_dup_socket:
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000106 __slots__.append("_base")
107
108 def __repr__(self):
109 """Wrap __repr__() to reveal the real class name."""
110 s = _socket.socket.__repr__(self)
111 if s.startswith("<socket object"):
112 s = "<%s.%s%s" % (self.__class__.__module__,
113 self.__class__.__name__,
114 s[7:])
115 return s
116
117 def accept(self):
118 """Wrap accept() to give the connection the right type."""
119 conn, addr = _socket.socket.accept(self)
120 fd = conn.fileno()
121 nfd = fd
Guido van Rossum93adc5d2007-07-17 20:41:19 +0000122 if _can_dup_socket:
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000123 nfd = os.dup(fd)
124 wrapper = socket(self.family, self.type, self.proto, fileno=nfd)
125 if fd == nfd:
126 wrapper._base = conn # Keep the base alive
127 else:
128 conn.close()
129 return wrapper, addr
130
Guido van Rossum93adc5d2007-07-17 20:41:19 +0000131 if not _can_dup_socket:
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000132 def close(self):
133 """Wrap close() to close the _base as well."""
134 _socket.socket.close(self)
135 base = getattr(self, "_base", None)
136 if base is not None:
137 base.close()
138
139 def makefile(self, mode="r", buffering=None, *,
140 encoding=None, newline=None):
141 """Return an I/O stream connected to the socket.
142
143 The arguments are as for io.open() after the filename,
144 except the only mode characters supported are 'r', 'w' and 'b'.
145 The semantics are similar too. (XXX refactor to share code?)
146 """
147 for c in mode:
148 if c not in {"r", "w", "b"}:
149 raise ValueError("invalid mode %r (only r, w, b allowed)")
150 writing = "w" in mode
151 reading = "r" in mode or not writing
152 assert reading or writing
153 binary = "b" in mode
154 rawmode = ""
155 if reading:
156 rawmode += "r"
157 if writing:
158 rawmode += "w"
159 raw = io.SocketIO(self, rawmode)
160 if buffering is None:
161 buffering = -1
162 if buffering < 0:
163 buffering = io.DEFAULT_BUFFER_SIZE
164 if buffering == 0:
165 if not binary:
166 raise ValueError("unbuffered streams must be binary")
167 raw.name = self.fileno()
168 raw.mode = mode
169 return raw
170 if reading and writing:
171 buffer = io.BufferedRWPair(raw, raw, buffering)
172 elif reading:
173 buffer = io.BufferedReader(raw, buffering)
174 else:
175 assert writing
176 buffer = io.BufferedWriter(raw, buffering)
177 if binary:
178 buffer.name = self.fileno()
179 buffer.mode = mode
180 return buffer
181 text = io.TextIOWrapper(buffer, encoding, newline)
182 text.name = self.fileno()
Guido van Rossum93adc5d2007-07-17 20:41:19 +0000183 text.mode = mode
Guido van Rossum7d0a8262007-05-21 23:13:11 +0000184 return text
185
Fred Drakea6070f02000-08-16 14:14:32 +0000186
187def getfqdn(name=''):
188 """Get fully qualified domain name from name.
189
190 An empty argument is interpreted as meaning the local host.
191
192 First the hostname returned by gethostbyaddr() is checked, then
193 possibly existing aliases. In case no FQDN is available, hostname
Brett Cannon01668a12005-03-11 00:04:17 +0000194 from gethostname() is returned.
Fred Drakea6070f02000-08-16 14:14:32 +0000195 """
196 name = name.strip()
Peter Schneider-Kamp2d2785a2000-08-16 20:30:21 +0000197 if not name or name == '0.0.0.0':
Fred Drakea6070f02000-08-16 14:14:32 +0000198 name = gethostname()
199 try:
200 hostname, aliases, ipaddrs = gethostbyaddr(name)
201 except error:
202 pass
203 else:
204 aliases.insert(0, hostname)
205 for name in aliases:
206 if '.' in name:
207 break
208 else:
209 name = hostname
210 return name
211
212
Guido van Rossumd8faa362007-04-27 19:54:29 +0000213def create_connection(address, timeout=None):
214 """Connect to address (host, port) with an optional timeout.
215
216 Provides access to socketobject timeout for higher-level
217 protocols. Passing a timeout will set the timeout on the
218 socket instance (if not present, or passed as None, the
219 default global timeout setting will be used).
220 """
221
222 msg = "getaddrinfo returns an empty list"
223 host, port = address
224 for res in getaddrinfo(host, port, 0, SOCK_STREAM):
225 af, socktype, proto, canonname, sa = res
226 sock = None
227 try:
228 sock = socket(af, socktype, proto)
229 if timeout is not None:
230 sock.settimeout(timeout)
231 sock.connect(sa)
232 return sock
233
234 except error as err:
235 msg = err
236 if sock is not None:
237 sock.close()
238
239 raise error(msg)