Python Network Programming
Python provides two levels of access to network services:
- Low-level network services support basic sockets, which provide the standard BSD Sockets API and give access to all methods of the underlying operating system's socket interface.
- The high-level network service module SocketServer provides server-centric classes that simplify the development of network servers.
What is a Socket?
Socket, also called a socket endpoint, is how applications usually send requests to or respond to requests from the network, allowing communication between hosts or between processes on a single computer.
The socket() function
In Python, we use the socket() function to create a socket. The syntax is as follows:
socket.socket([family[, type[, proto]]])
Parameters
- family: The socket family can be AF_UNIX or AF_INET.
- type: the socket type can be divided according to whether it is connection-oriented or connectionless
SOCK_STREAMorSOCK_DGRAM. - protocol: Generally left unspecified, defaulting to 0.
Socket object (built-in) methods
| function | Description |
|---|---|
| Server-side sockets | |
| s.bind() | Bind an address (host, port) to the socket. Under AF_INET, the address is represented as a tuple (host, port). |
| s.listen() | Start TCP listening. backlog specifies the maximum number of connections the operating system can hold pending before refusing connections. The value must be at least 1; most applications set it to 5. |
| s.accept() | Passively accept a TCP client connection, (blocking) waiting for a connection to arrive |
| Client-side sockets | |
| s.connect() | Actively initiate a TCP server connection. Generally the address format is a tuple (hostname, port); if the connection fails, a socket.error error is returned. |
| s.connect_ex() | An extended version of the connect() function that returns an error code instead of raising an exception when an error occurs |
| Socket functions for general use | |
| s.recv() | Receive TCP data; the data is returned as a string. bufsize specifies the maximum amount of data to receive. flag provides additional information about the message and can usually be ignored. |
| s.send() | Send TCP data, sending the data in string to the connected socket. The return value is the number of bytes to be sent, which may be smaller than the byte size of string. |
| s.sendall() | Send TCP data in full. Send the data in string to the connected socket, but try to send all the data before returning. Return None on success, or raise an exception on failure. |
| s.recvfrom() | Receive UDP data, similar to recv(), but the return value is (data, address). Here data is a string containing the received data, and address is the socket address of the sender. |
| s.sendto() | Send UDP data, sending the data to the socket. address is a tuple of the form (ipaddr, port) specifying the remote address. The return value is the number of bytes sent. |
| s.close() | Close the socket |
| s.getpeername() | Return the remote address of the connected socket. The return value is usually a tuple (ipaddr, port). |
| s.getsockname() | Return the socket's own address. Usually a tuple (ipaddr, port) |
| s.setsockopt(level,optname,value) | Set the value of the given socket option. |
| s.getsockopt(level,optname[.buflen]) | Return the value of a socket option. |
| s.settimeout(timeout) | Set a timeout period for socket operations; timeout is a floating-point number in seconds. A value of None means there is no timeout period. Generally the timeout should be set right after creating the socket, since it may be used for connection operations (such as connect()) |
| s.gettimeout() | Return the current timeout value in seconds, or None if no timeout has been set. |
| s.fileno() | Return the socket's file descriptor. |
| s.setblocking(flag) | If flag is 0, set the socket to non-blocking mode; otherwise set it to blocking mode (the default). In non-blocking mode, if a call to recv() finds no data, or a call to send() cannot send data immediately, a socket.error exception will be raised. |
| s.makefile() | Create a file object associated with this socket |
Simple Example
Server side
We use the socket module's socket function to create a socket object. The socket object can set up a socket service by calling other functions.
Now we can call the bind(hostname, port) function to specify the service's port.
Next, we call the socket object's accept method. This method waits for a client connection and returns a connection object representing the connection to the client.
The complete code is as follows:
Example
#!/usr/bin/python
-- coding: UTF-8 --
Filename: server.py
import
socket
Import the socket module
s
=
socket
.
socket
(
)
Create a socket object
host
=
socket
.
gethostname
(
)
Get the local host name
port
=
12345
Set the port
s
.
bind
(
(
host
,
port
)
)
Bind the port
s
.
listen
(
5
)
Wait for a client connection
while
True
:
c
,
addr
=
s
.
accept
(
)
Establish the client connection
'
Connection address:
'
,
addr
c
.
send
(
'
Welcome to Runoob Tutorial!
'
)
c
.
close
(
)
Close the Connection
Client Side
Next, we write a simple client example to connect to the service created above. The port number is 12345.
socket.connect(hostname, port ) method opens a TCP connection to the host hostname and the port port of the service provider. After connecting we can get data from the server; remember to close the connection when finished.
The complete code is as follows:
Example
#!/usr/bin/python
-- coding: UTF-8 --
Filename: client.py
import
socket
Import the socket module
s
=
socket
.
socket
(
)
Create a socket object
host
=
socket
.
gethostname
(
)
Get the local host name
port
=
12345
Set the port number
s
.
connect
(
(
host
,
port
)
)
s
.
recv
(
1024
)
s
.
close
(
)
Now we open two terminals; in the first terminal run the server.py file:
$ python server.py
In the second terminal run the client.py file:
$ python client.py
欢迎访问Runoob Tutorial!
Now if we go back to the first terminal, we will see the following output:
连接地址: ('192.168.0.118', 62461)
Python Internet modules
The following lists some important modules for Python network programming:
| Protocol | Purpose | Port number | Python module |
|---|---|---|---|
| HTTP | Web page access | 80 | httplib, urllib, xmlrpclib |
| NNTP | Read and post news articles, commonly called "posts" | 119 | nntplib |
| FTP | File transfer | 20 | ftplib, urllib |
| SMTP | Send email | 25 | smtplib |
| POP3 | Receive email | 110 | poplib |
| IMAP4 | Retrieve email | 143 | imaplib |
| Telnet | Command line | 23 | telnetlib |
| Gopher | Information lookup | 70 | gopherlib, urllib |
For more content, see the official site's Python Socket Library and Modules.