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 # These classes are used by the socket() defined on Windows and BeOS
126 # platforms to provide a best-effort implementation of the cleanup
127 # semantics needed when sockets can't be dup()ed.
129 # These are not actually used on other platforms.
133 'bind', 'connect', 'connect_ex', 'fileno', 'listen',
134 'getpeername', 'getsockname', 'getsockopt', 'setsockopt',
135 'sendall', 'setblocking',
136 'settimeout', 'gettimeout', 'shutdown')
138 if sys
.platform
== "riscos":
139 _socketmethods
= _socketmethods
+ ('sleeptaskw',)
141 class _closedsocket(object):
144 raise error(EBADF
, 'Bad file descriptor')
145 send
= recv
= sendto
= recvfrom
= __getattr__
= _dummy
147 class _socketobject(object):
149 __doc__
= _realsocket
.__doc
__
151 __slots__
= ["_sock", "send", "recv", "sendto", "recvfrom",
154 def __init__(self
, family
=AF_INET
, type=SOCK_STREAM
, proto
=0, _sock
=None):
156 _sock
= _realsocket(family
, type, proto
)
158 self
.send
= self
._sock
.send
159 self
.recv
= self
._sock
.recv
160 self
.sendto
= self
._sock
.sendto
161 self
.recvfrom
= self
._sock
.recvfrom
164 self
._sock
= _closedsocket()
165 self
.send
= self
.recv
= self
.sendto
= self
.recvfrom
= self
._sock
._dummy
166 close
.__doc
__ = _realsocket
.close
.__doc
__
169 sock
, addr
= self
._sock
.accept()
170 return _socketobject(_sock
=sock
), addr
171 accept
.__doc
__ = _realsocket
.accept
.__doc
__
174 """dup() -> socket object
176 Return a new socket object connected to the same system resource."""
177 return _socketobject(_sock
=self
._sock
)
179 def makefile(self
, mode
='r', bufsize
=-1):
180 """makefile([mode[, bufsize]]) -> file object
182 Return a regular file object corresponding to the socket. The mode
183 and bufsize arguments are as for the built-in open() function."""
184 return _fileobject(self
._sock
, mode
, bufsize
)
186 _s
= ("def %s(self, *args): return self._sock.%s(*args)\n\n"
187 "%s.__doc__ = _realsocket.%s.__doc__\n")
188 for _m
in _socketmethods
:
189 exec _s
% (_m
, _m
, _m
, _m
)
192 socket
= SocketType
= _socketobject
194 class _fileobject(object):
195 """Faux file object attached to a socket object."""
197 default_bufsize
= 8192
200 __slots__
= ["mode", "bufsize", "softspace",
201 # "closed" is a property, see below
202 "_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf"]
204 def __init__(self
, sock
, mode
='rb', bufsize
=-1):
206 self
.mode
= mode
# Not actually used in this version
208 bufsize
= self
.default_bufsize
209 self
.bufsize
= bufsize
210 self
.softspace
= False
214 self
._rbufsize
= self
.default_bufsize
216 self
._rbufsize
= bufsize
217 self
._wbufsize
= bufsize
218 self
._rbuf
= "" # A string
219 self
._wbuf
= [] # A list of strings
221 def _getclosed(self
):
222 return self
._sock
is None
223 closed
= property(_getclosed
, doc
="True if the file is closed")
236 # close() may fail if __init__ didn't complete
241 buffer = "".join(self
._wbuf
)
243 self
._sock
.sendall(buffer)
246 return self
._sock
.fileno()
248 def write(self
, data
):
249 data
= str(data
) # XXX Should really reject non-string non-buffers
252 self
._wbuf
.append(data
)
253 if (self
._wbufsize
== 0 or
254 self
._wbufsize
== 1 and '\n' in data
or
255 self
._get
_wbuf
_len
() >= self
._wbufsize
):
258 def writelines(self
, list):
259 # XXX We could do better here for very long lists
260 # XXX Should really reject non-string non-buffers
261 self
._wbuf
.extend(filter(None, map(str, list)))
262 if (self
._wbufsize
<= 1 or
263 self
._get
_wbuf
_len
() >= self
._wbufsize
):
266 def _get_wbuf_len(self
):
272 def read(self
, size
=-1):
280 if self
._rbufsize
<= 1:
281 recv_size
= self
.default_bufsize
283 recv_size
= self
._rbufsize
285 data
= self
._sock
.recv(recv_size
)
289 return "".join(buffers
)
291 # Read until size bytes or EOF seen, whichever comes first
294 self
._rbuf
= data
[size
:]
301 left
= size
- buf_len
302 recv_size
= max(self
._rbufsize
, left
)
303 data
= self
._sock
.recv(recv_size
)
309 self
._rbuf
= data
[left
:]
310 buffers
[-1] = data
[:left
]
313 return "".join(buffers
)
315 def readline(self
, size
=-1):
318 # Read until \n or EOF, whichever comes first
319 if self
._rbufsize
<= 1:
320 # Speed up unbuffered case
323 recv
= self
._sock
.recv
329 return "".join(buffers
)
333 self
._rbuf
= data
[nl
:]
340 data
= self
._sock
.recv(self
._rbufsize
)
347 self
._rbuf
= data
[nl
:]
348 buffers
[-1] = data
[:nl
]
350 return "".join(buffers
)
352 # Read until size bytes or \n or EOF seen, whichever comes first
353 nl
= data
.find('\n', 0, size
)
356 self
._rbuf
= data
[nl
:]
360 self
._rbuf
= data
[size
:]
367 data
= self
._sock
.recv(self
._rbufsize
)
371 left
= size
- buf_len
372 nl
= data
.find('\n', 0, left
)
375 self
._rbuf
= data
[nl
:]
376 buffers
[-1] = data
[:nl
]
380 self
._rbuf
= data
[left
:]
381 buffers
[-1] = data
[:left
]
384 return "".join(buffers
)
386 def readlines(self
, sizehint
=0):
390 line
= self
.readline()
395 if sizehint
and total
>= sizehint
:
405 line
= self
.readline()