Python Network Programming

Python provides network services at two levels of access:

  • Low-level network services support basic Sockets, providing the standard BSD Sockets API, which can access all methods of the underlying operating system Socket interface.
  • The high-level network service module SocketServer provides server-centric classes that simplify the development of network servers.

What is a Socket?

A Socket is also called a 'socket'. Applications usually make requests to the network or respond to network requests through the 'socket', enabling communication between hosts or between processes on the same computer.


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 into:SOCK_STREAMorSOCK_DGRAM。
  • protocol: Generally not filled in; the default is 0.

Socket Object (Built-in) Methods

Function Description
Server-side sockets
s.bind() Bind the address (host, port) to the socket. Under AF_INET, the address is represented in the form of a tuple (host, port).
s.listen() Start TCP listening. backlog specifies the maximum number of connections the operating system can queue before refusing connections. This value must be at least 1; for most applications, setting it to 5 is sufficient.
s.accept() Passively accept TCP client connections, waiting (blocking) for the connection to arrive.
Client-side sockets
s.connect() Actively initialize a TCP server connection. Generally, address is in the form of a tuple (hostname, port). If the connection fails, a socket.error is returned.
s.connect_ex() An extended version of the connect() function; on error, it returns an error code rather than raising an exception.
Socket functions for common 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. Sends the data in string to the connected socket. The return value is the number of bytes sent, which may be less than the byte size of string.
s.sendall() Send TCP data completely. Sends the data in string to the connected socket, but attempts to send all data before returning. Returns None on success, or raises an exception on failure.
s.recvfrom() Receive UDP data, similar to recv(), but the return value is (data, address). data is a string containing the received data, and address is the socket address that sent the data.
s.sendto() Send UDP data. Sends data to the socket; address is a tuple in the form of (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 the socket option.
s.settimeout(timeout) Set the timeout period for socket operations. timeout is a float in seconds. A value of None means no timeout period. Generally, the timeout should be set when the socket is first created, because it may be used for connection operations (such as connect()).
s.gettimeout() Return the current timeout value in seconds; if no timeout period is set, return None.
s.fileno() Return the file descriptor of the socket.
s.setblocking(flag) If flag is 0, set the socket to non-blocking mode; otherwise set the socket to blocking mode (default). In non-blocking mode, if recv() finds no data, or send() cannot send data immediately, it will raise a socket.error exception.
s.makefile() Create a file associated with this socket.

Simple Example

Server

We use the socket module'ssocketfunction to create a socket object. The socket object can set up a socket service by calling other functions.

Now we can call thebind(hostname, port)function to specify the service'sport.。

Next, we call the socket object'sacceptmethod. This method waits for a client connection and returns aconnectionobject, indicating that it is connected to the client.

The complete code is as follows:

Example

#!/usr/bin/python # -*- coding: UTF-8 -*- # File name: server.py import socket # Import socket module s = socket.socket() # Create socket object host = socket.gethostname() # Get local host name port = 12345 # Set port s.bind((host, port)) # Bind port s.listen(5) # Wait for client connection while True: c,addr = s.accept() # Establish client connection print 'Connection address:', addr c.send('Welcome to Example!') c.close() # Close connection

Client

Next, let's 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 hosthostnameand portportof the server. Once connected, we can retrieve data from the server. Remember to close the connection after operations are complete.

The complete code is as follows:

Example

#!/usr/bin/python # -*- coding: UTF-8 -*- # File name: client.py import socket # Import socket module s = socket.socket() # Create socket object host = socket.gethostname() # Get local host name port = 12345 # Set port number s.connect((host, port)) print s.recv(1024) s.close()

Now let's 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 
欢迎访问Example!

At this point, if we open the first terminal again, we will see the following output:

连接地址: ('192.168.0.118', 62461)

Python Internet Modules

The following lists some important modules for Python network programming:

ProtocolFunction/PurposePort numberPython Module
HTTPWeb access80httplib, urllib, xmlrpclib
NNTPRead and post news articles, commonly known as "posts".119nntplib
FTPFile transfer20ftplib, urllib
SMTPSend email25smtplib
POP3Receive email110poplib
IMAP4Fetch email143imaplib
TelnetCommand-line23telnetlib
GopherInformation lookup70gopherlib, urllib

For more information, refer to the official website'sPython Socket Library and Modules。

Other extensions.