Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 1 | # Wrapper module for _socket, providing some additional facilities |
| 2 | # implemented in Python. |
| 3 | |
| 4 | """\ |
| 5 | This module provides socket operations and some related functions. |
| 6 | On Unix, it supports IP (Internet Protocol) and Unix domain sockets. |
Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 7 | On other systems, it only supports IP. Functions specific for a |
Martin v. Löwis | af484d5 | 2000-09-30 11:34:30 +0000 | [diff] [blame] | 8 | socket are available as methods of the socket object. |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 9 | |
| 10 | Functions: |
| 11 | |
| 12 | socket() -- create a new socket object |
Dave Cole | 331708b | 2004-08-09 04:51:41 +0000 | [diff] [blame] | 13 | socketpair() -- create a pair of new socket objects [*] |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 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() -- mape 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 | ssl() -- secure socket layer support (only available if configured) |
Guido van Rossum | 9d0c8ce | 2002-07-18 17:08:35 +0000 | [diff] [blame] | 25 | socket.getdefaulttimeout() -- get the default timeout value |
| 26 | socket.setdefaulttimeout() -- set the default timeout value |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 27 | create_connection() -- connects to an address, with an optional timeout |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 28 | |
| 29 | [*] not available on all platforms! |
| 30 | |
| 31 | Special objects: |
| 32 | |
| 33 | SocketType -- type object for socket objects |
| 34 | error -- exception raised for I/O errors |
Guido van Rossum | 47dfa4a | 2003-04-25 05:48:32 +0000 | [diff] [blame] | 35 | has_ipv6 -- boolean value indicating if IPv6 is supported |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 36 | |
| 37 | Integer constants: |
| 38 | |
| 39 | AF_INET, AF_UNIX -- socket domains (first argument to socket() call) |
| 40 | SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument) |
| 41 | |
| 42 | Many other constants may be defined; these may be used in calls to |
| 43 | the setsockopt() and getsockopt() methods. |
| 44 | """ |
| 45 | |
Tim Peters | 18e6778 | 2002-02-17 04:25:24 +0000 | [diff] [blame] | 46 | import _socket |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 47 | from _socket import * |
Tim Peters | 18e6778 | 2002-02-17 04:25:24 +0000 | [diff] [blame] | 48 | |
Guido van Rossum | c18993f | 2002-08-08 15:16:20 +0000 | [diff] [blame] | 49 | _have_ssl = False |
Marc-André Lemburg | a5d2b4c | 2002-02-16 18:23:30 +0000 | [diff] [blame] | 50 | try: |
Guido van Rossum | de7cade | 2002-08-08 15:25:28 +0000 | [diff] [blame] | 51 | import _ssl |
Marc-André Lemburg | a5d2b4c | 2002-02-16 18:23:30 +0000 | [diff] [blame] | 52 | from _ssl import * |
Guido van Rossum | c18993f | 2002-08-08 15:16:20 +0000 | [diff] [blame] | 53 | _have_ssl = True |
Marc-André Lemburg | a5d2b4c | 2002-02-16 18:23:30 +0000 | [diff] [blame] | 54 | except ImportError: |
Guido van Rossum | c18993f | 2002-08-08 15:16:20 +0000 | [diff] [blame] | 55 | pass |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 56 | |
Guido van Rossum | 7d0a826 | 2007-05-21 23:13:11 +0000 | [diff] [blame] | 57 | import os, sys, io |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 58 | |
Fred Drake | 70d566b | 2003-04-29 19:50:25 +0000 | [diff] [blame] | 59 | try: |
| 60 | from errno import EBADF |
| 61 | except ImportError: |
| 62 | EBADF = 9 |
| 63 | |
Skip Montanaro | 0de6580 | 2001-02-15 22:15:14 +0000 | [diff] [blame] | 64 | __all__ = ["getfqdn"] |
Skip Montanaro | 0de6580 | 2001-02-15 22:15:14 +0000 | [diff] [blame] | 65 | __all__.extend(os._get_exports_list(_socket)) |
Guido van Rossum | de7cade | 2002-08-08 15:25:28 +0000 | [diff] [blame] | 66 | if _have_ssl: |
| 67 | __all__.extend(os._get_exports_list(_ssl)) |
Skip Montanaro | 0de6580 | 2001-02-15 22:15:14 +0000 | [diff] [blame] | 68 | |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 69 | # WSA error codes |
| 70 | if 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 Montanaro | 64de1a4 | 2001-03-18 19:53:21 +0000 | [diff] [blame] | 87 | __all__.append("errorTab") |
Guido van Rossum | de7cade | 2002-08-08 15:25:28 +0000 | [diff] [blame] | 88 | |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 89 | |
Guido van Rossum | 93adc5d | 2007-07-17 20:41:19 +0000 | [diff] [blame] | 90 | # 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 | |
| 94 | if _can_dup_socket: |
Guido van Rossum | 7d0a826 | 2007-05-21 23:13:11 +0000 | [diff] [blame] | 95 | 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 | |
| 100 | class socket(_socket.socket): |
| 101 | |
| 102 | """A subclass of _socket.socket adding the makefile() method.""" |
| 103 | |
| 104 | __slots__ = ["__weakref__"] |
Guido van Rossum | 93adc5d | 2007-07-17 20:41:19 +0000 | [diff] [blame] | 105 | if not _can_dup_socket: |
Guido van Rossum | 7d0a826 | 2007-05-21 23:13:11 +0000 | [diff] [blame] | 106 | __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 Rossum | 93adc5d | 2007-07-17 20:41:19 +0000 | [diff] [blame] | 122 | if _can_dup_socket: |
Guido van Rossum | 7d0a826 | 2007-05-21 23:13:11 +0000 | [diff] [blame] | 123 | 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 Rossum | 93adc5d | 2007-07-17 20:41:19 +0000 | [diff] [blame] | 131 | if not _can_dup_socket: |
Guido van Rossum | 7d0a826 | 2007-05-21 23:13:11 +0000 | [diff] [blame] | 132 | 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 Rossum | 93adc5d | 2007-07-17 20:41:19 +0000 | [diff] [blame] | 183 | text.mode = mode |
Guido van Rossum | 7d0a826 | 2007-05-21 23:13:11 +0000 | [diff] [blame] | 184 | return text |
| 185 | |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 186 | |
| 187 | def 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 Cannon | 01668a1 | 2005-03-11 00:04:17 +0000 | [diff] [blame] | 194 | from gethostname() is returned. |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 195 | """ |
| 196 | name = name.strip() |
Peter Schneider-Kamp | 2d2785a | 2000-08-16 20:30:21 +0000 | [diff] [blame] | 197 | if not name or name == '0.0.0.0': |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 198 | 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 Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 213 | def 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) |