1 # Wrapper module for _socket, providing some additional facilities
2 # implemented in Python.
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.
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!
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
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.
51 from errno
import EBADF
55 __all__
= ["getfqdn", "create_connection"]
56 __all__
.extend(os
._get
_exports
_list
(_socket
))
62 if sys
.platform
.lower().startswith("win"):
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
)
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 "",
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())
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?)
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
143 raw
= SocketIO(self
, rawmode
)
145 if buffering
is None:
148 buffering
= io
.DEFAULT_BUFFER_SIZE
151 raise ValueError("unbuffered streams must be binary")
153 if reading
and writing
:
154 buffer = io
.BufferedRWPair(raw
, raw
, buffering
)
156 buffer = io
.BufferedReader(raw
, buffering
)
159 buffer = io
.BufferedWriter(raw
, buffering
)
162 text
= io
.TextIOWrapper(buffer, encoding
, newline
)
166 def _decref_socketios(self
):
167 if self
._io
_refs
> 0:
172 def _real_close(self
):
173 _socket
.socket
.close(self
)
177 if self
._io
_refs
<= 0:
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().
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.
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
)
208 self
._reading
= "r" in mode
209 self
._writing
= "w" in mode
211 def readinto(self
, b
):
213 self
._checkReadable
()
214 return self
._sock
.recv_into(b
)
218 self
._checkWritable
()
219 return self
._sock
.send(b
)
222 return self
._reading
and not self
.closed
225 return self
._writing
and not self
.closed
229 return self
._sock
.fileno()
242 io
.RawIOBase
.close(self
)
243 self
._sock
._decref
_socketios
()
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.
261 if not name
or name
== '0.0.0.0':
264 hostname
, aliases
, ipaddrs
= gethostbyaddr(name
)
268 aliases
.insert(0, hostname
)
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`
290 msg
= "getaddrinfo returns an empty list"
292 for res
in getaddrinfo(host
, port
, 0, SOCK_STREAM
):
293 af
, socktype
, proto
, canonname
, sa
= res
296 sock
= socket(af
, socktype
, proto
)
297 if timeout
is not _GLOBAL_DEFAULT_TIMEOUT
:
298 sock
.settimeout(timeout
)