Create and return a new socket object to use IP v4 and TCP.
| Return type: | socket object |
|---|
Example usage:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Set options on the socket.
Example usage:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
There are many different socket options that can be set. The one set here, socket.SO_REUSEADDR, causes the port to be released immediately after the socket is closed. Without this option, if you restart the program right away after a previous exit, then a socket.bind() system call could fail reporting that the port is already in use.
Bind to a particular port in preparation to receive connections on this port. bind() takes one parameter, which is a two value tuple consisting of a hostname (string) and port number (integer). Notice the double parentheses – the tuple is often generated as bind() is being called.
| Parm hostname: | The hostnames to accept connections from, usually ‘’, which will accept from any host. It may also be ‘localhost’ for security reasons. |
|---|---|
| Parm port: | The port number to bind to. Must not already be in use. |
Example usage:
sock.bind((hostname, port))
Begin listening on the previously bound port for new connections.
| Parameters: | n (integer) – The number of simultaneous connections to queue waiting for service. |
|---|---|
| Limit n: | 5 |
Example usage:
sock.listen(n)
Accept a new connection.
| Return type: | socket |
|---|
Example usage:
(newsock, address) = sock.accept()
Establish a connection to a server.
Example usage:
sock.connect((hostname, portNumber))
Receive up to N bytes from the socket. Block until a message is received on the socket, or the connection was closed.
| Return type: | string |
|---|
Example usage:
message = sock.recv(1024)
Note
The only time that recv() will return with no data., i.e., if len(message) == 0: or if not message: (these two statements are equivalent) is when the connection was closed, usually by the far end closing the socket. Thus, testing for a zero length message is the usual way of detecting a disconnect. See close() and shutdown().
Send a string message using an established socket connection.
| Parameters: | msg (string) – The message to send |
|---|
Example usage:
sock.send(msg)
Close an established socket connection.
Example usage:
sock.close()
Leave the socket open, but discontinue using it in one of three ways.
| Parameters: | n – Which function of the socket is discontinued. 0 = done receiving, 1 = done sending, 2 = both |
|---|
Example usage:
sock.shutdown(1)
In most cases shutdown() is not used. If the far end is looping on recv(), when the near end does sock.shutdown(1), then the connection is still active, but the far end will receive a zero length message. The far end could still send some final data back to the near end. Some application layer protocols call for the use of shutdown(). If you are not expecting the far end to perform a shutdown(); however, then it is usually safe to assume that a zero length message is due to a close().
Here is an example of when you might want to use shutdown(). This is the determined sender and the patient receiver. The sender is trying to send a large amount of data, so it sends multiple 1024 byte blocks. After sending all of the data, the sender does a shutdown() to signal to the receiver that all of the data has been sent. At this point, the sender can not send any more data, but it can receive data. When the receiver gets the zero length message, it sends back the size of the data received. If the receiver does not report the same value as was sent, the determined sender re-connects and tries to send the data again.
# This is the 'determined sender'
import socket
import string
try_send = True
while try_send:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((server, 4000))
buffer = orig_data
sent = 0
while len(buffer) > 1024:
sent += sock.send(buffer[:1024])
buffer = buffer[1024:]
sock.send(buffer)
sock.shutdown(1)
received = sock.recv(30)
sock.close()
if string.atoi(received) == sent:
try_send = False
else:
print "Not all data sent"
The receiver sends back the size of the data received after the shutdown() and then waits for another connection.
# This is the patient receiver
import socket
ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ss.bind(('', 4000))
ss.listen(1)
while True:
new,addr = ss.accept()
buffer = ""
block = 'x'
while block:
block = new.recv(1024)
buffer += block
# -- end of data
new.send(len(buffer))
new.close()
handle_new_stuff(buffer)
Resolves the host/port argument, into a sequence of 5-tuples that contain all the necessary arguments for creating the corresponding socket. port is a string service name such as ‘http’, a numeric port number or None. Additional arguments (not shown here) are optional.
The getaddrinfo() function returns a list of 5-tuples with the following structure:
(family, socktype, proto, canonname, sockaddr)
family, socktype, proto are all integers and are meant to be passed to the socket() function. canonname is a string representing the canonical name of the host.
Translate a host name to IPv4 address format.
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).