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
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.
59 from errno
import EBADF
64 __all__
.extend(os
._get
_exports
_list
(_socket
))
66 __all__
.extend(os
._get
_exports
_list
(_ssl
))
71 def ssl(sock
, keyfile
=None, certfile
=None):
72 if hasattr(sock
, "_sock"):
74 return _realssl(sock
, keyfile
, certfile
)
77 if sys
.platform
.lower().startswith("win"):
79 errorTab
[10004] = "The operation was interrupted."
80 errorTab
[10009] = "A bad file handle was passed."
81 errorTab
[10013] = "Permission denied."
82 errorTab
[10014] = "A fault occurred on the network??" # WSAEFAULT
83 errorTab
[10022] = "An invalid operation was attempted."
84 errorTab
[10035] = "The socket operation would block"
85 errorTab
[10036] = "A blocking operation is already in progress."
86 errorTab
[10048] = "The network address is in use."
87 errorTab
[10054] = "The connection has been reset."
88 errorTab
[10058] = "The network has been shut down."
89 errorTab
[10060] = "The operation timed out."
90 errorTab
[10061] = "Connection refused."
91 errorTab
[10063] = "The name is too long."
92 errorTab
[10064] = "The host is down."
93 errorTab
[10065] = "The host is unreachable."
94 __all__
.append("errorTab")
99 """Get fully qualified domain name from name.
101 An empty argument is interpreted as meaning the local host.
103 First the hostname returned by gethostbyaddr() is checked, then
104 possibly existing aliases. In case no FQDN is available, hostname
105 from gethostname() is returned.
108 if not name
or name
== '0.0.0.0':
111 hostname
, aliases
, ipaddrs
= gethostbyaddr(name
)
115 aliases
.insert(0, hostname
)
125 'bind', 'connect', 'connect_ex', 'fileno', 'listen',
126 'getpeername', 'getsockname', 'getsockopt', 'setsockopt',
127 'sendall', 'setblocking',
128 'settimeout', 'gettimeout', 'shutdown')
130 if sys
.platform
== "riscos":
131 _socketmethods
= _socketmethods
+ ('sleeptaskw',)
133 # All the method names that must be delegated to either the real socket
134 # object or the _closedsocket object.
135 _delegate_methods
= ("recv", "recvfrom", "recv_into", "recvfrom_into",
138 class _closedsocket(object):
141 raise error(EBADF
, 'Bad file descriptor')
144 # All _delegate_methods must also be initialized here.
145 send
= recv
= recv_into
= sendto
= recvfrom
= recvfrom_into
= _dummy
148 class _socketobject(object):
150 __doc__
= _realsocket
.__doc
__
152 __slots__
= ["_sock", "__weakref__"] + list(_delegate_methods
)
154 def __init__(self
, family
=AF_INET
, type=SOCK_STREAM
, proto
=0, _sock
=None):
156 _sock
= _realsocket(family
, type, proto
)
158 for method
in _delegate_methods
:
159 setattr(self
, method
, getattr(_sock
, method
))
163 self
._sock
= _closedsocket()
164 dummy
= self
._sock
._dummy
165 for method
in _delegate_methods
:
166 setattr(self
, method
, dummy
)
167 close
.__doc
__ = _realsocket
.close
.__doc
__
170 sock
, addr
= self
._sock
.accept()
171 return _socketobject(_sock
=sock
), addr
172 accept
.__doc
__ = _realsocket
.accept
.__doc
__
175 """dup() -> socket object
177 Return a new socket object connected to the same system resource."""
178 return _socketobject(_sock
=self
._sock
)
180 def makefile(self
, mode
='r', bufsize
=-1):
181 """makefile([mode[, bufsize]]) -> file object
183 Return a regular file object corresponding to the socket. The mode
184 and bufsize arguments are as for the built-in open() function."""
185 return _fileobject(self
._sock
, mode
, bufsize
)
187 family
= property(lambda self
: self
._sock
.family
, doc
="the socket family")
188 type = property(lambda self
: self
._sock
.type, doc
="the socket type")
189 proto
= property(lambda self
: self
._sock
.proto
, doc
="the socket protocol")
191 _s
= ("def %s(self, *args): return self._sock.%s(*args)\n\n"
192 "%s.__doc__ = _realsocket.%s.__doc__\n")
193 for _m
in _socketmethods
:
194 exec _s
% (_m
, _m
, _m
, _m
)
197 socket
= SocketType
= _socketobject
199 class _fileobject(object):
200 """Faux file object attached to a socket object."""
202 default_bufsize
= 8192
205 __slots__
= ["mode", "bufsize", "softspace",
206 # "closed" is a property, see below
207 "_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf"]
209 def __init__(self
, sock
, mode
='rb', bufsize
=-1):
211 self
.mode
= mode
# Not actually used in this version
213 bufsize
= self
.default_bufsize
214 self
.bufsize
= bufsize
215 self
.softspace
= False
219 self
._rbufsize
= self
.default_bufsize
221 self
._rbufsize
= bufsize
222 self
._wbufsize
= bufsize
223 self
._rbuf
= "" # A string
224 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")
241 # close() may fail if __init__ didn't complete
246 buffer = "".join(self
._wbuf
)
248 self
._sock
.sendall(buffer)
251 return self
._sock
.fileno()
253 def write(self
, data
):
254 data
= str(data
) # XXX Should really reject non-string non-buffers
257 self
._wbuf
.append(data
)
258 if (self
._wbufsize
== 0 or
259 self
._wbufsize
== 1 and '\n' in data
or
260 self
._get
_wbuf
_len
() >= self
._wbufsize
):
263 def writelines(self
, list):
264 # XXX We could do better here for very long lists
265 # XXX Should really reject non-string non-buffers
266 self
._wbuf
.extend(filter(None, map(str, list)))
267 if (self
._wbufsize
<= 1 or
268 self
._get
_wbuf
_len
() >= self
._wbufsize
):
271 def _get_wbuf_len(self
):
277 def read(self
, size
=-1):
285 if self
._rbufsize
<= 1:
286 recv_size
= self
.default_bufsize
288 recv_size
= self
._rbufsize
290 data
= self
._sock
.recv(recv_size
)
294 return "".join(buffers
)
296 # Read until size bytes or EOF seen, whichever comes first
299 self
._rbuf
= data
[size
:]
306 left
= size
- buf_len
307 recv_size
= max(self
._rbufsize
, left
)
308 data
= self
._sock
.recv(recv_size
)
314 self
._rbuf
= data
[left
:]
315 buffers
[-1] = data
[:left
]
318 return "".join(buffers
)
320 def readline(self
, size
=-1):
323 # Read until \n or EOF, whichever comes first
324 if self
._rbufsize
<= 1:
325 # Speed up unbuffered case
328 recv
= self
._sock
.recv
334 return "".join(buffers
)
338 self
._rbuf
= data
[nl
:]
345 data
= self
._sock
.recv(self
._rbufsize
)
352 self
._rbuf
= data
[nl
:]
353 buffers
[-1] = data
[:nl
]
355 return "".join(buffers
)
357 # Read until size bytes or \n or EOF seen, whichever comes first
358 nl
= data
.find('\n', 0, size
)
361 self
._rbuf
= data
[nl
:]
365 self
._rbuf
= data
[size
:]
372 data
= self
._sock
.recv(self
._rbufsize
)
376 left
= size
- buf_len
377 nl
= data
.find('\n', 0, left
)
380 self
._rbuf
= data
[nl
:]
381 buffers
[-1] = data
[:nl
]
385 self
._rbuf
= data
[left
:]
386 buffers
[-1] = data
[:left
]
389 return "".join(buffers
)
391 def readlines(self
, sizehint
=0):
395 line
= self
.readline()
400 if sizehint
and total
>= sizehint
:
410 line
= self
.readline()