blob: 03cdc65f764225a2ce12af33ddc7bf01683f40be [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 Rossum7d0a8262007-05-21 23:13:11 +000090_os_has_dup = hasattr(os, "dup")
91if _os_has_dup:
92 def fromfd(fd, family=AF_INET, type=SOCK_STREAM, proto=0):
93 nfd = os.dup(fd)
94 return socket(family, type, proto, fileno=nfd)
95
96
97class socket(_socket.socket):
98
99 """A subclass of _socket.socket adding the makefile() method."""
100
101 __slots__ = ["__weakref__"]
102 if not _os_has_dup:
103 __slots__.append("_base")
104
105 def __repr__(self):
106 """Wrap __repr__() to reveal the real class name."""
107 s = _socket.socket.__repr__(self)
108 if s.startswith("<socket object"):
109 s = "<%s.%s%s" % (self.__class__.__module__,
110 self.__class__.__name__,
111 s[7:])
112 return s
113
114 def accept(self):
115 """Wrap accept() to give the connection the right type."""
116 conn, addr = _socket.socket.accept(self)
117 fd = conn.fileno()
118 nfd = fd
119 if _os_has_dup:
120 nfd = os.dup(fd)
121 wrapper = socket(self.family, self.type, self.proto, fileno=nfd)
122 if fd == nfd:
123 wrapper._base = conn # Keep the base alive
124 else:
125 conn.close()
126 return wrapper, addr
127
128 if not _os_has_dup:
129 def close(self):
130 """Wrap close() to close the _base as well."""
131 _socket.socket.close(self)
132 base = getattr(self, "_base", None)
133 if base is not None:
134 base.close()
135
136 def makefile(self, mode="r", buffering=None, *,
137 encoding=None, newline=None):
138 """Return an I/O stream connected to the socket.
139
140 The arguments are as for io.open() after the filename,
141 except the only mode characters supported are 'r', 'w' and 'b'.
142 The semantics are similar too. (XXX refactor to share code?)
143 """
144 for c in mode:
145 if c not in {"r", "w", "b"}:
146 raise ValueError("invalid mode %r (only r, w, b allowed)")
147 writing = "w" in mode
148 reading = "r" in mode or not writing
149 assert reading or writing
150 binary = "b" in mode
151 rawmode = ""
152 if reading:
153 rawmode += "r"
154 if writing:
155 rawmode += "w"
156 raw = io.SocketIO(self, rawmode)
157 if buffering is None:
158 buffering = -1
159 if buffering < 0:
160 buffering = io.DEFAULT_BUFFER_SIZE
161 if buffering == 0:
162 if not binary:
163 raise ValueError("unbuffered streams must be binary")
164 raw.name = self.fileno()
165 raw.mode = mode
166 return raw
167 if reading and writing:
168 buffer = io.BufferedRWPair(raw, raw, buffering)
169 elif reading:
170 buffer = io.BufferedReader(raw, buffering)
171 else:
172 assert writing
173 buffer = io.BufferedWriter(raw, buffering)
174 if binary:
175 buffer.name = self.fileno()
176 buffer.mode = mode
177 return buffer
178 text = io.TextIOWrapper(buffer, encoding, newline)
179 text.name = self.fileno()
180 self.mode = mode
181 return text
182
Fred Drakea6070f02000-08-16 14:14:32 +0000183
184def getfqdn(name=''):
185 """Get fully qualified domain name from name.
186
187 An empty argument is interpreted as meaning the local host.
188
189 First the hostname returned by gethostbyaddr() is checked, then
190 possibly existing aliases. In case no FQDN is available, hostname
Brett Cannon01668a12005-03-11 00:04:17 +0000191 from gethostname() is returned.
Fred Drakea6070f02000-08-16 14:14:32 +0000192 """
193 name = name.strip()
Peter Schneider-Kamp2d2785a2000-08-16 20:30:21 +0000194 if not name or name == '0.0.0.0':
Fred Drakea6070f02000-08-16 14:14:32 +0000195 name = gethostname()
196 try:
197 hostname, aliases, ipaddrs = gethostbyaddr(name)
198 except error:
199 pass
200 else:
201 aliases.insert(0, hostname)
202 for name in aliases:
203 if '.' in name:
204 break
205 else:
206 name = hostname
207 return name
208
209
Guido van Rossumd8faa362007-04-27 19:54:29 +0000210def create_connection(address, timeout=None):
211 """Connect to address (host, port) with an optional timeout.
212
213 Provides access to socketobject timeout for higher-level
214 protocols. Passing a timeout will set the timeout on the
215 socket instance (if not present, or passed as None, the
216 default global timeout setting will be used).
217 """
218
219 msg = "getaddrinfo returns an empty list"
220 host, port = address
221 for res in getaddrinfo(host, port, 0, SOCK_STREAM):
222 af, socktype, proto, canonname, sa = res
223 sock = None
224 try:
225 sock = socket(af, socktype, proto)
226 if timeout is not None:
227 sock.settimeout(timeout)
228 sock.connect(sa)
229 return sock
230
231 except error as err:
232 msg = err
233 if sock is not None:
234 sock.close()
235
236 raise error(msg)