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 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.
48 from functools
import partial
49 from types
import MethodType
57 def ssl(sock
, keyfile
=None, certfile
=None):
58 # we do an internal import here because the ssl
59 # module imports the socket module
60 import ssl
as _realssl
61 warnings
.warn("socket.ssl() is deprecated. Use ssl.wrap_socket() instead.",
62 DeprecationWarning, stacklevel
=2)
63 return _realssl
.sslwrap_simple(sock
, keyfile
, certfile
)
65 # we need to import the same constants we used to...
66 from _ssl
import SSLError
as sslerror
71 SSL_ERROR_ZERO_RETURN
, \
72 SSL_ERROR_WANT_READ
, \
73 SSL_ERROR_WANT_WRITE
, \
74 SSL_ERROR_WANT_X509_LOOKUP
, \
77 SSL_ERROR_WANT_CONNECT
, \
79 SSL_ERROR_INVALID_ERROR_CODE
81 import os
, sys
, warnings
84 from cStringIO
import StringIO
86 from StringIO
import StringIO
92 EBADF
= getattr(errno
, 'EBADF', 9)
93 EINTR
= getattr(errno
, 'EINTR', 4)
95 __all__
= ["getfqdn", "create_connection"]
96 __all__
.extend(os
._get
_exports
_list
(_socket
))
102 if sys
.platform
.lower().startswith("win"):
104 errorTab
[10004] = "The operation was interrupted."
105 errorTab
[10009] = "A bad file handle was passed."
106 errorTab
[10013] = "Permission denied."
107 errorTab
[10014] = "A fault occurred on the network??" # WSAEFAULT
108 errorTab
[10022] = "An invalid operation was attempted."
109 errorTab
[10035] = "The socket operation would block"
110 errorTab
[10036] = "A blocking operation is already in progress."
111 errorTab
[10048] = "The network address is in use."
112 errorTab
[10054] = "The connection has been reset."
113 errorTab
[10058] = "The network has been shut down."
114 errorTab
[10060] = "The operation timed out."
115 errorTab
[10061] = "Connection refused."
116 errorTab
[10063] = "The name is too long."
117 errorTab
[10064] = "The host is down."
118 errorTab
[10065] = "The host is unreachable."
119 __all__
.append("errorTab")
123 def getfqdn(name
=''):
124 """Get fully qualified domain name from name.
126 An empty argument is interpreted as meaning the local host.
128 First the hostname returned by gethostbyaddr() is checked, then
129 possibly existing aliases. In case no FQDN is available, hostname
130 from gethostname() is returned.
133 if not name
or name
== '0.0.0.0':
136 hostname
, aliases
, ipaddrs
= gethostbyaddr(name
)
140 aliases
.insert(0, hostname
)
150 'bind', 'connect', 'connect_ex', 'fileno', 'listen',
151 'getpeername', 'getsockname', 'getsockopt', 'setsockopt',
152 'sendall', 'setblocking',
153 'settimeout', 'gettimeout', 'shutdown')
156 _socketmethods
= _socketmethods
+ ('ioctl',)
158 if sys
.platform
== "riscos":
159 _socketmethods
= _socketmethods
+ ('sleeptaskw',)
161 # All the method names that must be delegated to either the real socket
162 # object or the _closedsocket object.
163 _delegate_methods
= ("recv", "recvfrom", "recv_into", "recvfrom_into",
166 class _closedsocket(object):
169 raise error(EBADF
, 'Bad file descriptor')
170 # All _delegate_methods must also be initialized here.
171 send
= recv
= recv_into
= sendto
= recvfrom
= recvfrom_into
= _dummy
174 # Wrapper around platform socket objects. This implements
175 # a platform-independent dup() functionality. The
176 # implementation currently relies on reference counting
177 # to close the underlying socket object.
178 class _socketobject(object):
180 __doc__
= _realsocket
.__doc
__
182 __slots__
= ["_sock", "__weakref__"] + list(_delegate_methods
)
184 def __init__(self
, family
=AF_INET
, type=SOCK_STREAM
, proto
=0, _sock
=None):
186 _sock
= _realsocket(family
, type, proto
)
188 for method
in _delegate_methods
:
189 setattr(self
, method
, getattr(_sock
, method
))
192 self
._sock
= _closedsocket()
193 dummy
= self
._sock
._dummy
194 for method
in _delegate_methods
:
195 setattr(self
, method
, dummy
)
196 close
.__doc
__ = _realsocket
.close
.__doc
__
199 sock
, addr
= self
._sock
.accept()
200 return _socketobject(_sock
=sock
), addr
201 accept
.__doc
__ = _realsocket
.accept
.__doc
__
204 """dup() -> socket object
206 Return a new socket object connected to the same system resource."""
207 return _socketobject(_sock
=self
._sock
)
209 def makefile(self
, mode
='r', bufsize
=-1):
210 """makefile([mode[, bufsize]]) -> file object
212 Return a regular file object corresponding to the socket. The mode
213 and bufsize arguments are as for the built-in open() function."""
214 return _fileobject(self
._sock
, mode
, bufsize
)
216 family
= property(lambda self
: self
._sock
.family
, doc
="the socket family")
217 type = property(lambda self
: self
._sock
.type, doc
="the socket type")
218 proto
= property(lambda self
: self
._sock
.proto
, doc
="the socket protocol")
220 def meth(name
,self
,*args
):
221 return getattr(self
._sock
,name
)(*args
)
223 for _m
in _socketmethods
:
226 p
.__doc
__ = getattr(_realsocket
,_m
).__doc
__
227 m
= MethodType(p
,None,_socketobject
)
228 setattr(_socketobject
,_m
,m
)
230 socket
= SocketType
= _socketobject
232 class _fileobject(object):
233 """Faux file object attached to a socket object."""
235 default_bufsize
= 8192
238 __slots__
= ["mode", "bufsize", "softspace",
239 # "closed" is a property, see below
240 "_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf", "_wbuf_len",
243 def __init__(self
, sock
, mode
='rb', bufsize
=-1, close
=False):
245 self
.mode
= mode
# Not actually used in this version
247 bufsize
= self
.default_bufsize
248 self
.bufsize
= bufsize
249 self
.softspace
= False
250 # _rbufsize is the suggested recv buffer size. It is *strictly*
251 # obeyed within readline() for recv calls. If it is larger than
252 # default_bufsize it will be used for recv calls within read().
256 self
._rbufsize
= self
.default_bufsize
258 self
._rbufsize
= bufsize
259 self
._wbufsize
= bufsize
260 # We use StringIO for the read buffer to avoid holding a list
261 # of variously sized string objects which have been known to
262 # fragment the heap due to how they are malloc()ed and often
263 # realloc()ed down much smaller than their original allocation.
264 self
._rbuf
= StringIO()
265 self
._wbuf
= [] # A list of strings
269 def _getclosed(self
):
270 return self
._sock
is None
271 closed
= property(_getclosed
, doc
="True if the file is closed")
286 # close() may fail if __init__ didn't complete
291 data
= "".join(self
._wbuf
)
294 buffer_size
= max(self
._rbufsize
, self
.default_bufsize
)
295 data_size
= len(data
)
297 view
= memoryview(data
)
299 while write_offset
< data_size
:
300 self
._sock
.sendall(view
[write_offset
:write_offset
+buffer_size
])
301 write_offset
+= buffer_size
303 if write_offset
< data_size
:
304 remainder
= data
[write_offset
:]
305 del view
, data
# explicit free
306 self
._wbuf
.append(remainder
)
307 self
._wbuf
_len
= len(remainder
)
310 return self
._sock
.fileno()
312 def write(self
, data
):
313 data
= str(data
) # XXX Should really reject non-string non-buffers
316 self
._wbuf
.append(data
)
317 self
._wbuf
_len
+= len(data
)
318 if (self
._wbufsize
== 0 or
319 self
._wbufsize
== 1 and '\n' in data
or
320 self
._wbuf
_len
>= self
._wbufsize
):
323 def writelines(self
, list):
324 # XXX We could do better here for very long lists
325 # XXX Should really reject non-string non-buffers
326 lines
= filter(None, map(str, list))
327 self
._wbuf
_len
+= sum(map(len, lines
))
328 self
._wbuf
.extend(lines
)
329 if (self
._wbufsize
<= 1 or
330 self
._wbuf
_len
>= self
._wbufsize
):
333 def read(self
, size
=-1):
334 # Use max, disallow tiny reads in a loop as they are very inefficient.
335 # We never leave read() with any leftover data from a new recv() call
336 # in our internal buffer.
337 rbufsize
= max(self
._rbufsize
, self
.default_bufsize
)
338 # Our use of StringIO rather than lists of string objects returned by
339 # recv() minimizes memory usage and fragmentation that occurs when
340 # rbufsize is large compared to the typical return value of recv().
342 buf
.seek(0, 2) # seek end
345 self
._rbuf
= StringIO() # reset _rbuf. we consume it via buf.
348 data
= self
._sock
.recv(rbufsize
)
350 if e
.args
[0] == EINTR
:
356 return buf
.getvalue()
358 # Read until size bytes or EOF seen, whichever comes first
361 # Already have size bytes in our buffer? Extract and return.
364 self
._rbuf
= StringIO()
365 self
._rbuf
.write(buf
.read())
368 self
._rbuf
= StringIO() # reset _rbuf. we consume it via buf.
370 left
= size
- buf_len
371 # recv() will malloc the amount of memory given as its
372 # parameter even though it often returns much less data
373 # than that. The returned data string is short lived
374 # as we copy it into a StringIO and free it. This avoids
375 # fragmentation issues on many platforms.
377 data
= self
._sock
.recv(left
)
379 if e
.args
[0] == EINTR
:
385 if n
== size
and not buf_len
:
386 # Shortcut. Avoid buffer data copies when:
387 # - We have no data in our buffer.
389 # - Our call to recv returned exactly the
390 # number of bytes we were asked to read.
394 del data
# explicit free
396 assert n
<= left
, "recv(%d) returned %d bytes" % (left
, n
)
399 del data
# explicit free
400 #assert buf_len == buf.tell()
401 return buf
.getvalue()
403 def readline(self
, size
=-1):
405 buf
.seek(0, 2) # seek end
407 # check if we already have it in our buffer
409 bline
= buf
.readline(size
)
410 if bline
.endswith('\n') or len(bline
) == size
:
411 self
._rbuf
= StringIO()
412 self
._rbuf
.write(buf
.read())
416 # Read until \n or EOF, whichever comes first
417 if self
._rbufsize
<= 1:
418 # Speed up unbuffered case
420 buffers
= [buf
.read()]
421 self
._rbuf
= StringIO() # reset _rbuf. we consume it via buf.
423 recv
= self
._sock
.recv
432 # The try..except to catch EINTR was moved outside the
433 # recv loop to avoid the per byte overhead.
434 if e
.args
[0] == EINTR
:
438 return "".join(buffers
)
440 buf
.seek(0, 2) # seek end
441 self
._rbuf
= StringIO() # reset _rbuf. we consume it via buf.
444 data
= self
._sock
.recv(self
._rbufsize
)
446 if e
.args
[0] == EINTR
:
455 self
._rbuf
.write(data
[nl
:])
459 return buf
.getvalue()
461 # Read until size bytes or \n or EOF seen, whichever comes first
462 buf
.seek(0, 2) # seek end
467 self
._rbuf
= StringIO()
468 self
._rbuf
.write(buf
.read())
470 self
._rbuf
= StringIO() # reset _rbuf. we consume it via buf.
473 data
= self
._sock
.recv(self
._rbufsize
)
475 if e
.args
[0] == EINTR
:
480 left
= size
- buf_len
481 # did we just receive a newline?
482 nl
= data
.find('\n', 0, left
)
485 # save the excess data to _rbuf
486 self
._rbuf
.write(data
[nl
:])
491 # Shortcut. Avoid data copy through buf when returning
492 # a substring of our first recv().
495 if n
== size
and not buf_len
:
496 # Shortcut. Avoid data copy through buf when
497 # returning exactly all of our first recv().
500 buf
.write(data
[:left
])
501 self
._rbuf
.write(data
[left
:])
505 #assert buf_len == buf.tell()
506 return buf
.getvalue()
508 def readlines(self
, sizehint
=0):
512 line
= self
.readline()
517 if sizehint
and total
>= sizehint
:
527 line
= self
.readline()
532 _GLOBAL_DEFAULT_TIMEOUT
= object()
534 def create_connection(address
, timeout
=_GLOBAL_DEFAULT_TIMEOUT
):
535 """Connect to *address* and return the socket object.
537 Convenience function. Connect to *address* (a 2-tuple ``(host,
538 port)``) and return the socket object. Passing the optional
539 *timeout* parameter will set the timeout on the socket instance
540 before attempting to connect. If no *timeout* is supplied, the
541 global default timeout setting returned by :func:`getdefaulttimeout`
545 msg
= "getaddrinfo returns an empty list"
547 for res
in getaddrinfo(host
, port
, 0, SOCK_STREAM
):
548 af
, socktype
, proto
, canonname
, sa
= res
551 sock
= socket(af
, socktype
, proto
)
552 if timeout
is not _GLOBAL_DEFAULT_TIMEOUT
:
553 sock
.settimeout(timeout
)