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() -- 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)
25 socket.getdefaulttimeout() -- get the default timeout value
26 socket.setdefaulttimeout() -- set the default timeout value
27 create_connection() -- connects to an address, with an optional timeout
29 [*] not available on all platforms!
33 SocketType -- type object for socket objects
34 error -- exception raised for I/O errors
35 has_ipv6 -- boolean value indicating if IPv6 is supported
39 AF_INET, AF_UNIX -- socket domains (first argument to socket() call)
40 SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)
42 Many other constants may be defined; these may be used in calls to
43 the setsockopt() and getsockopt() methods.
60 from errno
import EBADF
65 __all__
.extend(os
._get
_exports
_list
(_socket
))
67 __all__
.extend(os
._get
_exports
_list
(_ssl
))
72 def ssl(sock
, keyfile
=None, certfile
=None):
73 if hasattr(sock
, "_sock"):
75 return _realssl(sock
, keyfile
, certfile
)
78 if sys
.platform
.lower().startswith("win"):
80 errorTab
[10004] = "The operation was interrupted."
81 errorTab
[10009] = "A bad file handle was passed."
82 errorTab
[10013] = "Permission denied."
83 errorTab
[10014] = "A fault occurred on the network??" # WSAEFAULT
84 errorTab
[10022] = "An invalid operation was attempted."
85 errorTab
[10035] = "The socket operation would block"
86 errorTab
[10036] = "A blocking operation is already in progress."
87 errorTab
[10048] = "The network address is in use."
88 errorTab
[10054] = "The connection has been reset."
89 errorTab
[10058] = "The network has been shut down."
90 errorTab
[10060] = "The operation timed out."
91 errorTab
[10061] = "Connection refused."
92 errorTab
[10063] = "The name is too long."
93 errorTab
[10064] = "The host is down."
94 errorTab
[10065] = "The host is unreachable."
95 __all__
.append("errorTab")
100 """Get fully qualified domain name from name.
102 An empty argument is interpreted as meaning the local host.
104 First the hostname returned by gethostbyaddr() is checked, then
105 possibly existing aliases. In case no FQDN is available, hostname
106 from gethostname() is returned.
109 if not name
or name
== '0.0.0.0':
112 hostname
, aliases
, ipaddrs
= gethostbyaddr(name
)
116 aliases
.insert(0, hostname
)
126 'bind', 'connect', 'connect_ex', 'fileno', 'listen',
127 'getpeername', 'getsockname', 'getsockopt', 'setsockopt',
128 'sendall', 'setblocking',
129 'settimeout', 'gettimeout', 'shutdown')
131 if sys
.platform
== "riscos":
132 _socketmethods
= _socketmethods
+ ('sleeptaskw',)
134 # All the method names that must be delegated to either the real socket
135 # object or the _closedsocket object.
136 _delegate_methods
= ("recv", "recvfrom", "recv_into", "recvfrom_into",
139 class _closedsocket(object):
142 raise error(EBADF
, 'Bad file descriptor')
143 # All _delegate_methods must also be initialized here.
144 send
= recv
= recv_into
= sendto
= recvfrom
= recvfrom_into
= _dummy
147 class _socketobject(object):
149 __doc__
= _realsocket
.__doc
__
151 __slots__
= ["_sock", "__weakref__"] + list(_delegate_methods
)
153 def __init__(self
, family
=AF_INET
, type=SOCK_STREAM
, proto
=0, _sock
=None):
155 _sock
= _realsocket(family
, type, proto
)
157 for method
in _delegate_methods
:
158 setattr(self
, method
, getattr(_sock
, method
))
161 self
._sock
= _closedsocket()
162 dummy
= self
._sock
._dummy
163 for method
in _delegate_methods
:
164 setattr(self
, method
, dummy
)
165 close
.__doc
__ = _realsocket
.close
.__doc
__
168 sock
, addr
= self
._sock
.accept()
169 return _socketobject(_sock
=sock
), addr
170 accept
.__doc
__ = _realsocket
.accept
.__doc
__
173 """dup() -> socket object
175 Return a new socket object connected to the same system resource."""
176 return _socketobject(_sock
=self
._sock
)
178 def makefile(self
, mode
='r', bufsize
=-1):
179 """makefile([mode[, bufsize]]) -> file object
181 Return a regular file object corresponding to the socket. The mode
182 and bufsize arguments are as for the built-in open() function."""
183 return _fileobject(self
._sock
, mode
, bufsize
)
185 family
= property(lambda self
: self
._sock
.family
, doc
="the socket family")
186 type = property(lambda self
: self
._sock
.type, doc
="the socket type")
187 proto
= property(lambda self
: self
._sock
.proto
, doc
="the socket protocol")
189 _s
= ("def %s(self, *args): return self._sock.%s(*args)\n\n"
190 "%s.__doc__ = _realsocket.%s.__doc__\n")
191 for _m
in _socketmethods
:
192 exec _s
% (_m
, _m
, _m
, _m
)
195 socket
= SocketType
= _socketobject
197 class _fileobject(object):
198 """Faux file object attached to a socket object."""
200 default_bufsize
= 8192
203 __slots__
= ["mode", "bufsize", "softspace",
204 # "closed" is a property, see below
205 "_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf",
208 def __init__(self
, sock
, mode
='rb', bufsize
=-1, close
=False):
210 self
.mode
= mode
# Not actually used in this version
212 bufsize
= self
.default_bufsize
213 self
.bufsize
= bufsize
214 self
.softspace
= False
218 self
._rbufsize
= self
.default_bufsize
220 self
._rbufsize
= bufsize
221 self
._wbufsize
= bufsize
222 self
._rbuf
= "" # A string
223 self
._wbuf
= [] # A list of strings
226 def _getclosed(self
):
227 return self
._sock
is None
228 closed
= property(_getclosed
, doc
="True if the file is closed")
243 # close() may fail if __init__ didn't complete
248 buffer = "".join(self
._wbuf
)
250 self
._sock
.sendall(buffer)
253 return self
._sock
.fileno()
255 def write(self
, data
):
256 data
= str(data
) # XXX Should really reject non-string non-buffers
259 self
._wbuf
.append(data
)
260 if (self
._wbufsize
== 0 or
261 self
._wbufsize
== 1 and '\n' in data
or
262 self
._get
_wbuf
_len
() >= self
._wbufsize
):
265 def writelines(self
, list):
266 # XXX We could do better here for very long lists
267 # XXX Should really reject non-string non-buffers
268 self
._wbuf
.extend(filter(None, map(str, list)))
269 if (self
._wbufsize
<= 1 or
270 self
._get
_wbuf
_len
() >= self
._wbufsize
):
273 def _get_wbuf_len(self
):
279 def read(self
, size
=-1):
287 if self
._rbufsize
<= 1:
288 recv_size
= self
.default_bufsize
290 recv_size
= self
._rbufsize
292 data
= self
._sock
.recv(recv_size
)
296 return "".join(buffers
)
298 # Read until size bytes or EOF seen, whichever comes first
301 self
._rbuf
= data
[size
:]
308 left
= size
- buf_len
309 recv_size
= max(self
._rbufsize
, left
)
310 data
= self
._sock
.recv(recv_size
)
316 self
._rbuf
= data
[left
:]
317 buffers
[-1] = data
[:left
]
320 return "".join(buffers
)
322 def readline(self
, size
=-1):
325 # Read until \n or EOF, whichever comes first
326 if self
._rbufsize
<= 1:
327 # Speed up unbuffered case
330 recv
= self
._sock
.recv
336 return "".join(buffers
)
340 self
._rbuf
= data
[nl
:]
347 data
= self
._sock
.recv(self
._rbufsize
)
354 self
._rbuf
= data
[nl
:]
355 buffers
[-1] = data
[:nl
]
357 return "".join(buffers
)
359 # Read until size bytes or \n or EOF seen, whichever comes first
360 nl
= data
.find('\n', 0, size
)
363 self
._rbuf
= data
[nl
:]
367 self
._rbuf
= data
[size
:]
374 data
= self
._sock
.recv(self
._rbufsize
)
378 left
= size
- buf_len
379 nl
= data
.find('\n', 0, left
)
382 self
._rbuf
= data
[nl
:]
383 buffers
[-1] = data
[:nl
]
387 self
._rbuf
= data
[left
:]
388 buffers
[-1] = data
[:left
]
391 return "".join(buffers
)
393 def readlines(self
, sizehint
=0):
397 line
= self
.readline()
402 if sizehint
and total
>= sizehint
:
412 line
= self
.readline()
418 def create_connection(address
, timeout
=None):
419 """Connect to address (host, port) with an optional timeout.
421 Provides access to socketobject timeout for higher-level
422 protocols. Passing a timeout will set the timeout on the
423 socket instance (if not present, or passed as None, the
424 default global timeout setting will be used).
427 msg
= "getaddrinfo returns an empty list"
429 for res
in getaddrinfo(host
, port
, 0, SOCK_STREAM
):
430 af
, socktype
, proto
, canonname
, sa
= res
433 sock
= socket(af
, socktype
, proto
)
434 if timeout
is not None:
435 sock
.settimeout(timeout
)