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 fromfd() -- create a socket object from an open file descriptor [*]
14 gethostname() -- return the current hostname
15 gethostbyname() -- map a hostname to its IP number
16 gethostbyaddr() -- map an IP number or hostname to DNS info
17 getservbyname() -- map a service name and a protocol name to a port number
18 getprotobyname() -- mape a protocol name (e.g. 'tcp') to a number
19 ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order
20 htons(), htonl() -- convert 16, 32 bit int from host to network byte order
21 inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format
22 inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89)
23 ssl() -- secure socket layer support (only available if configured)
24 socket.getdefaulttimeout() -- get the default timeout value
25 socket.setdefaulttimeout() -- set the default timeout value
27 [*] not available on all platforms!
31 SocketType -- type object for socket objects
32 error -- exception raised for I/O errors
33 has_ipv6 -- boolean value indicating if IPv6 is supported
37 AF_INET, AF_UNIX -- socket domains (first argument to socket() call)
38 SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)
40 Many other constants may be defined; these may be used in calls to
41 the setsockopt() and getsockopt() methods.
58 __all__
.extend(os
._get
_exports
_list
(_socket
))
60 __all__
.extend(os
._get
_exports
_list
(_ssl
))
63 if (sys
.platform
.lower().startswith("win")
64 or (hasattr(os
, 'uname') and os
.uname()[0] == "BeOS")
65 or sys
.platform
=="riscos"):
69 def ssl(sock
, keyfile
=None, certfile
=None):
70 if hasattr(sock
, "_sock"):
72 return _realssl(sock
, keyfile
, certfile
)
75 if sys
.platform
.lower().startswith("win"):
77 errorTab
[10004] = "The operation was interrupted."
78 errorTab
[10009] = "A bad file handle was passed."
79 errorTab
[10013] = "Permission denied."
80 errorTab
[10014] = "A fault occurred on the network??" # WSAEFAULT
81 errorTab
[10022] = "An invalid operation was attempted."
82 errorTab
[10035] = "The socket operation would block"
83 errorTab
[10036] = "A blocking operation is already in progress."
84 errorTab
[10048] = "The network address is in use."
85 errorTab
[10054] = "The connection has been reset."
86 errorTab
[10058] = "The network has been shut down."
87 errorTab
[10060] = "The operation timed out."
88 errorTab
[10061] = "Connection refused."
89 errorTab
[10063] = "The name is too long."
90 errorTab
[10064] = "The host is down."
91 errorTab
[10065] = "The host is unreachable."
92 __all__
.append("errorTab")
98 """Get fully qualified domain name from name.
100 An empty argument is interpreted as meaning the local host.
102 First the hostname returned by gethostbyaddr() is checked, then
103 possibly existing aliases. In case no FQDN is available, hostname
107 if not name
or name
== '0.0.0.0':
110 hostname
, aliases
, ipaddrs
= gethostbyaddr(name
)
114 aliases
.insert(0, hostname
)
124 # These classes are used by the socket() defined on Windows and BeOS
125 # platforms to provide a best-effort implementation of the cleanup
126 # semantics needed when sockets can't be dup()ed.
128 # These are not actually used on other platforms.
132 'bind', 'connect', 'connect_ex', 'fileno', 'listen',
133 'getpeername', 'getsockname', 'getsockopt', 'setsockopt',
134 'recv', 'recvfrom', 'send', 'sendall', 'sendto', 'setblocking',
135 'settimeout', 'gettimeout', 'shutdown')
137 class _closedsocket(object):
139 def __getattr__(self
, name
):
140 raise error(9, 'Bad file descriptor')
142 class _socketobject(object):
144 __doc__
= _realsocket
.__doc
__
146 __slots__
= ["_sock"]
148 def __init__(self
, family
=AF_INET
, type=SOCK_STREAM
, proto
=0, _sock
=None):
150 _sock
= _realsocket(family
, type, proto
)
154 self
._sock
= _closedsocket()
155 close
.__doc
__ = _realsocket
.close
.__doc
__
158 sock
, addr
= self
._sock
.accept()
159 return _socketobject(_sock
=sock
), addr
160 accept
.__doc
__ = _realsocket
.accept
.__doc
__
163 """dup() -> socket object
165 Return a new socket object connected to the same system resource."""
166 return _socketobject(_sock
=self
._sock
)
168 def makefile(self
, mode
='r', bufsize
=-1):
169 """makefile([mode[, bufsize]]) -> file object
171 Return a regular file object corresponding to the socket. The mode
172 and bufsize arguments are as for the built-in open() function."""
173 return _fileobject(self
._sock
, mode
, bufsize
)
175 _s
= ("def %s(self, *args): return self._sock.%s(*args)\n\n"
176 "%s.__doc__ = _realsocket.%s.__doc__\n")
177 for _m
in _socketmethods
:
178 exec _s
% (_m
, _m
, _m
, _m
)
181 socket
= SocketType
= _socketobject
183 class _fileobject(object):
184 """Faux file object attached to a socket object."""
186 default_bufsize
= 8192
189 __slots__
= ["mode", "bufsize", "softspace",
190 # "closed" is a property, see below
191 "_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf"]
193 def __init__(self
, sock
, mode
='rb', bufsize
=-1):
195 self
.mode
= mode
# Not actually used in this version
197 bufsize
= self
.default_bufsize
198 self
.bufsize
= bufsize
199 self
.softspace
= False
203 self
._rbufsize
= self
.default_bufsize
205 self
._rbufsize
= bufsize
206 self
._wbufsize
= bufsize
207 self
._rbuf
= "" # A string
208 self
._wbuf
= [] # A list of strings
210 def _getclosed(self
):
211 return self
._sock
is not None
212 closed
= property(_getclosed
, doc
="True if the file is closed")
226 buffer = "".join(self
._wbuf
)
228 self
._sock
.sendall(buffer)
231 return self
._sock
.fileno()
233 def write(self
, data
):
234 data
= str(data
) # XXX Should really reject non-string non-buffers
237 self
._wbuf
.append(data
)
238 if (self
._wbufsize
== 0 or
239 self
._wbufsize
== 1 and '\n' in data
or
240 self
._get
_wbuf
_len
() >= self
._wbufsize
):
243 def writelines(self
, list):
244 # XXX We could do better here for very long lists
245 # XXX Should really reject non-string non-buffers
246 self
._wbuf
.extend(filter(None, map(str, list)))
247 if (self
._wbufsize
<= 1 or
248 self
._get
_wbuf
_len
() >= self
._wbufsize
):
251 def _get_wbuf_len(self
):
257 def read(self
, size
=-1):
265 if self
._rbufsize
<= 1:
266 recv_size
= self
.default_bufsize
268 recv_size
= self
._rbufsize
270 data
= self
._sock
.recv(recv_size
)
274 return "".join(buffers
)
276 # Read until size bytes or EOF seen, whichever comes first
279 self
._rbuf
= data
[size
:]
286 left
= size
- buf_len
287 recv_size
= max(self
._rbufsize
, left
)
288 data
= self
._sock
.recv(recv_size
)
294 self
._rbuf
= data
[left
:]
295 buffers
[-1] = data
[:left
]
298 return "".join(buffers
)
300 def readline(self
, size
=-1):
303 # Read until \n or EOF, whichever comes first
304 if self
._rbufsize
<= 1:
305 # Speed up unbuffered case
308 recv
= self
._sock
.recv
314 return "".join(buffers
)
318 self
._rbuf
= data
[nl
:]
325 data
= self
._sock
.recv(self
._rbufsize
)
332 self
._rbuf
= data
[nl
:]
333 buffers
[-1] = data
[:nl
]
335 return "".join(buffers
)
337 # Read until size bytes or \n or EOF seen, whichever comes first
338 nl
= data
.find('\n', 0, size
)
341 self
._rbuf
= data
[nl
:]
345 self
._rbuf
= data
[size
:]
352 data
= self
._sock
.recv(self
._rbufsize
)
356 left
= size
- buf_len
357 nl
= data
.find('\n', 0, left
)
360 self
._rbuf
= data
[nl
:]
361 buffers
[-1] = data
[:nl
]
365 self
._rbuf
= data
[left
:]
366 buffers
[-1] = data
[:left
]
369 return "".join(buffers
)
371 def readlines(self
, sizehint
=0):
375 line
= self
.readline()
380 if sizehint
and total
>= sizehint
:
390 line
= self
.readline()