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 from errno
import EBADF
63 __all__
.extend(os
._get
_exports
_list
(_socket
))
65 __all__
.extend(os
._get
_exports
_list
(_ssl
))
68 if (sys
.platform
.lower().startswith("win")
69 or (hasattr(os
, 'uname') and os
.uname()[0] == "BeOS")
70 or sys
.platform
=="riscos"):
74 def ssl(sock
, keyfile
=None, certfile
=None):
75 if hasattr(sock
, "_sock"):
77 return _realssl(sock
, keyfile
, certfile
)
80 if sys
.platform
.lower().startswith("win"):
82 errorTab
[10004] = "The operation was interrupted."
83 errorTab
[10009] = "A bad file handle was passed."
84 errorTab
[10013] = "Permission denied."
85 errorTab
[10014] = "A fault occurred on the network??" # WSAEFAULT
86 errorTab
[10022] = "An invalid operation was attempted."
87 errorTab
[10035] = "The socket operation would block"
88 errorTab
[10036] = "A blocking operation is already in progress."
89 errorTab
[10048] = "The network address is in use."
90 errorTab
[10054] = "The connection has been reset."
91 errorTab
[10058] = "The network has been shut down."
92 errorTab
[10060] = "The operation timed out."
93 errorTab
[10061] = "Connection refused."
94 errorTab
[10063] = "The name is too long."
95 errorTab
[10064] = "The host is down."
96 errorTab
[10065] = "The host is unreachable."
97 __all__
.append("errorTab")
101 def getfqdn(name
=''):
102 """Get fully qualified domain name from name.
104 An empty argument is interpreted as meaning the local host.
106 First the hostname returned by gethostbyaddr() is checked, then
107 possibly existing aliases. In case no FQDN is available, hostname
111 if not name
or name
== '0.0.0.0':
114 hostname
, aliases
, ipaddrs
= gethostbyaddr(name
)
118 aliases
.insert(0, hostname
)
128 # These classes are used by the socket() defined on Windows and BeOS
129 # platforms to provide a best-effort implementation of the cleanup
130 # semantics needed when sockets can't be dup()ed.
132 # These are not actually used on other platforms.
136 'bind', 'connect', 'connect_ex', 'fileno', 'listen',
137 'getpeername', 'getsockname', 'getsockopt', 'setsockopt',
138 'sendall', 'setblocking',
139 'settimeout', 'gettimeout', 'shutdown')
141 if sys
.platform
== "riscos":
142 _socketmethods
= _socketmethods
+ ('sleeptaskw',)
144 class _closedsocket(object):
147 raise error(EBADF
, 'Bad file descriptor')
148 send
= recv
= sendto
= recvfrom
= __getattr__
= _dummy
150 class _socketobject(object):
152 __doc__
= _realsocket
.__doc
__
154 __slots__
= ["_sock", "send", "recv", "sendto", "recvfrom"]
156 def __init__(self
, family
=AF_INET
, type=SOCK_STREAM
, proto
=0, _sock
=None):
158 _sock
= _realsocket(family
, type, proto
)
160 self
.send
= self
._sock
.send
161 self
.recv
= self
._sock
.recv
162 self
.sendto
= self
._sock
.sendto
163 self
.recvfrom
= self
._sock
.recvfrom
166 self
._sock
= _closedsocket()
167 self
.send
= self
.recv
= self
.sendto
= self
.recvfrom
= self
._sock
._dummy
168 close
.__doc
__ = _realsocket
.close
.__doc
__
171 sock
, addr
= self
._sock
.accept()
172 return _socketobject(_sock
=sock
), addr
173 accept
.__doc
__ = _realsocket
.accept
.__doc
__
176 """dup() -> socket object
178 Return a new socket object connected to the same system resource."""
179 return _socketobject(_sock
=self
._sock
)
181 def makefile(self
, mode
='r', bufsize
=-1):
182 """makefile([mode[, bufsize]]) -> file object
184 Return a regular file object corresponding to the socket. The mode
185 and bufsize arguments are as for the built-in open() function."""
186 return _fileobject(self
._sock
, mode
, bufsize
)
188 _s
= ("def %s(self, *args): return self._sock.%s(*args)\n\n"
189 "%s.__doc__ = _realsocket.%s.__doc__\n")
190 for _m
in _socketmethods
:
191 exec _s
% (_m
, _m
, _m
, _m
)
194 socket
= SocketType
= _socketobject
196 class _fileobject(object):
197 """Faux file object attached to a socket object."""
199 default_bufsize
= 8192
202 __slots__
= ["mode", "bufsize", "softspace",
203 # "closed" is a property, see below
204 "_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf"]
206 def __init__(self
, sock
, mode
='rb', bufsize
=-1):
208 self
.mode
= mode
# Not actually used in this version
210 bufsize
= self
.default_bufsize
211 self
.bufsize
= bufsize
212 self
.softspace
= False
216 self
._rbufsize
= self
.default_bufsize
218 self
._rbufsize
= bufsize
219 self
._wbufsize
= bufsize
220 self
._rbuf
= "" # A string
221 self
._wbuf
= [] # A list of strings
223 def _getclosed(self
):
224 return self
._sock
is not None
225 closed
= property(_getclosed
, doc
="True if the file is closed")
238 # close() may fail if __init__ didn't complete
243 buffer = "".join(self
._wbuf
)
245 self
._sock
.sendall(buffer)
248 return self
._sock
.fileno()
250 def write(self
, data
):
251 data
= str(data
) # XXX Should really reject non-string non-buffers
254 self
._wbuf
.append(data
)
255 if (self
._wbufsize
== 0 or
256 self
._wbufsize
== 1 and '\n' in data
or
257 self
._get
_wbuf
_len
() >= self
._wbufsize
):
260 def writelines(self
, list):
261 # XXX We could do better here for very long lists
262 # XXX Should really reject non-string non-buffers
263 self
._wbuf
.extend(filter(None, map(str, list)))
264 if (self
._wbufsize
<= 1 or
265 self
._get
_wbuf
_len
() >= self
._wbufsize
):
268 def _get_wbuf_len(self
):
274 def read(self
, size
=-1):
282 if self
._rbufsize
<= 1:
283 recv_size
= self
.default_bufsize
285 recv_size
= self
._rbufsize
287 data
= self
._sock
.recv(recv_size
)
291 return "".join(buffers
)
293 # Read until size bytes or EOF seen, whichever comes first
296 self
._rbuf
= data
[size
:]
303 left
= size
- buf_len
304 recv_size
= max(self
._rbufsize
, left
)
305 data
= self
._sock
.recv(recv_size
)
311 self
._rbuf
= data
[left
:]
312 buffers
[-1] = data
[:left
]
315 return "".join(buffers
)
317 def readline(self
, size
=-1):
320 # Read until \n or EOF, whichever comes first
321 if self
._rbufsize
<= 1:
322 # Speed up unbuffered case
325 recv
= self
._sock
.recv
331 return "".join(buffers
)
335 self
._rbuf
= data
[nl
:]
342 data
= self
._sock
.recv(self
._rbufsize
)
349 self
._rbuf
= data
[nl
:]
350 buffers
[-1] = data
[:nl
]
352 return "".join(buffers
)
354 # Read until size bytes or \n or EOF seen, whichever comes first
355 nl
= data
.find('\n', 0, size
)
358 self
._rbuf
= data
[nl
:]
362 self
._rbuf
= data
[size
:]
369 data
= self
._sock
.recv(self
._rbufsize
)
373 left
= size
- buf_len
374 nl
= data
.find('\n', 0, left
)
377 self
._rbuf
= data
[nl
:]
378 buffers
[-1] = data
[:nl
]
382 self
._rbuf
= data
[left
:]
383 buffers
[-1] = data
[:left
]
386 return "".join(buffers
)
388 def readlines(self
, sizehint
=0):
392 line
= self
.readline()
397 if sizehint
and total
>= sizehint
:
407 line
= self
.readline()