Socket Module - Python Library
Este documento é uma transcrição parcial da documentação do
módulo socket da biblioteca
(library) da linguagem Python. Apenas as funções mais comuns de
uma aplicação Cliente-Servidor foram transcritas e sua ordem foi alterada
de modo a seguir a sequencia típica de chamadas de uma aplicação Cliente-Servidor
(Prof. Célio G - fev 2010).
This module provides access to the BSD socket interface. It is available on
all modern Unix systems, Windows, Mac OS X, BeOS, OS/2, and probably additional
platforms.
The Python interface is a straightforward transliteration of the Unix system
call and library interface for sockets to Python’s object-oriented style: the
socket() function returns a
socket object whose methods implement
the various socket system calls. Parameter types are somewhat higher-level than
in the C interface: as with read()
and write() operations on Python
files, buffer allocation on receive operations is automatic, and buffer length
is implicit on send operations.
Socket addresses are represented as follows: A single string is used for the
AF_UNIX address family. A pair
(host, port) is used for the
AF_INET address family, where host
is a string representing either a
hostname in Internet domain notation like 'daring.cwi.nl'
or an IPv4 address like '100.50.200.5',
and port is an integral port number.
For IPv4 addresses, two special forms are accepted instead of a host address:
the empty string represents INADDR_ANY,
and the string '<broadcast>'
represents INADDR_BROADCAST
The module socket exports
the following constants and functions:
-
socket.AF_UNIX
-
socket.AF_INET
-
socket.AF_INET6
- These constants represent the address (and protocol) families, used for the
first argument to
socket(). If the
AF_UNIX constant is not
defined then this protocol is unsupported.
-
socket.SOCK_STREAM
-
socket.SOCK_DGRAM
-
socket.SOCK_RAW
-
socket.SOCK_RDM
-
socket.SOCK_SEQPACKET
- These constants represent the socket types, used for the second argument to
socket(). (Only SOCK_STREAM
and
SOCK_DGRAM appear to be
generally useful.)
As funções que se seguem são as funções básicas de uma aplicação Cliente_Servidor (Célio G.)
-
socket.socket([family[, type[, proto]]])
- Create a new socket using the given address family, socket type and protocol
number. The address family should be AF_INET (the default),
AF_INET6 or AF_UNIX.
The socket type should be
SOCK_STREAM (the default),
SOCK_DGRAM or perhaps one of the
other SOCK_ constants.
The protocol number is usually zero and may be
omitted in that case.
-
socket.bind(address)
Bind the socket to address. The socket must not already be bound. (The format
of address depends on the address family — see above.)
-
socket.listen(backlog
)
- Listen for connections made to the socket. The backlog argument specifies the
maximum number of queued connections and should be at least 1; the maximum value
is system-dependent (usually 5).
-
socket.accept()
- Accept a connection. The socket must be bound to an address and listening for
connections. The return value is a pair (conn,
address) where conn is a
new socket object usable to send and receive data on the connection, and
address is the address bound to the socket on the other end of the connection.
-
socket.recv(bufsize
[, flags])
Receive data from the socket. The return value is a string representing the
data received. The maximum amount of data to be received at once is specified
by bufsize. See the Unix manual page recv(2) for the meaning of
the optional argument flags; it defaults to zero.
-
socket.send(string
[, flags])
- Send data to the socket. The socket must be connected to a remote socket. The
optional flags argument has the same meaning as for recv() above.
Returns the number of bytes sent. Applications are responsible for checking that
all data has been sent; if only some of the data was transmitted, the
application needs to attempt delivery of the remaining data.
-
socket.sendall(string
[, flags])
- Send data to the socket. The socket must be connected to a remote socket. The
optional flags argument has the same meaning as for
recv() above.
Unlike
send(),
this method continues to send data from string until
either all data has been sent or an error occurs.
None is returned on
success. On error, an exception is raised, and there is no way to determine how
much data, if any, was successfully sent.
-
socket.connect(address
)
Connect to a remote socket at address. (The format of address depends on the
address family — see above.)
-
socket.close()
- Close the socket. All future operations on the socket object will fail. The
remote end will receive no more data (after queued data is flushed). Sockets are
automatically closed when they are garbage-collected.
-
socket.shutdown(how)
- Shut down one or both halves of the connection. If how is
SHUT_RD,
further receives are disallowed. If how is
SHUT_WR, further sends
are disallowed. If how is
SHUT_RDWR, further sends and receives are
disallowed.
Funções de suporte - as funções a seguir essencialmente fazem conversões de nomes simbólicos
para endereços IP (ou números de porta) e vice-versa (Célio G)
-
socket.gethostbyname(hostname
)
- Translate a host name to IPv4 address format. The IPv4 address is returned as a
string, such as '100.50.200.5'.
If the host name is an IPv4 address itself
it is returned unchanged. See gethostbyname_ex()
for a more complete
interface.
gethostbyname()
does not support IPv6 name resolution, and
tt class="xref docutils literal">getaddrinfo() should be
used instead for IPv4/v6 dual stack support.
-
socket.gethostname()
Return a string containing the hostname of the machine where the Python
interpreter is currently executing.
If you want to know the current machine’s IP address, you may want to use
gethostbyname(gethostname()).
This operation assumes that there is a
valid address-to-host mapping for the host, and the assumption does not
always hold.
-
socket.gethostbyaddr(
ip_address)
- Return a triple (hostname,
aliaslist, ipaddrlist)
where hostname is the
primary host name responding to the given ip_address, aliaslist is a
(possibly empty) list of alternative host names for the same address, and
ipaddrlist is a list of IPv4/v6 addresses for the same interface on the same
host (most likely containing only a single address). To find the fully qualified
domain name, use the function getfqdn().
gethostbyaddr() supports
both IPv4 and IPv6.
-
socket.getservbyname(
servicename[, protocolname]
)
- Translate an Internet service name and protocol name to a port number for that
service. The optional protocol name, if given, should be
'tcp' or
'udp', otherwise any protocol will match.
18.2.2 Example
Here are four minimal example programs using the TCP/IP protocol: a server that echoes all data
that it receives back (servicing only one client), and a client using it.
Note that a server must perform the sequence socket(), bind(), listen(), accept()
(possibly repeating the accept() to service more than one client), while a client only needs
the sequence socket(), connect(). Also note that the server does not send()/recv() on the socket
it is listening on but on the new socket returned by accept().
The first two examples support IPv4 only.
# Echo server program
import socket
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()
# Echo client program
import socket
HOST = 'xaveco.lab.ic.unicamp.br' # The remote host
PORT = 50007 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)