Python3 Network Programming

Python provides network services at two levels:

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

What is a Socket?

Socket, also known as a "socket", is used by applications to send requests to the network or respond to network requests, enabling communication between hosts or between processes on the same computer.


socket() Function

In Python, we use the socket() function to create a socket, and 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 based on whether it is connection-oriented or connectionless:SOCK_STREAMorSOCK_DGRAM
  • proto: Generally left blank, defaults to 0.

Socket Object (Built-in) Methods

Function Description
Server-side Socket
s.bind() Binds the address (host, port) to the socket. Under AF_INET, the address is represented in the form of a tuple (host, port).
s.listen() Starts TCP listening. backlog specifies the maximum number of connections the operating system can queue before refusing connections. This value must be at least 1, and for most applications, setting it to 5 is sufficient.
s.accept() Passively accepts TCP client connections, (blocking) waiting for the connection to arrive
Client-side Socket
s.connect() Actively initializes a TCP server connection. Generally, the format of address is a tuple (hostname, port). If the connection fails, a socket.error is returned.
s.connect_ex() An extended version of the connect() function, returns an error code on failure instead of raising an exception
Public-purpose Socket Functions
s.recv() Receives TCP data, 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() Sends TCP data, sending the data from string to the connected socket. The return value is the number of bytes sent, which may be less than the byte size of the string.
s.sendall() Completely sends TCP data. Sends the data from string to the connected socket, but attempts to send all data before returning. Returns None on success, raises an exception on failure.
s.recvfrom() Receives 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 from which the data was sent.
s.sendto() Sends UDP data, sending the data to the socket. address is a tuple in the form (ipaddr, port) specifying the remote address. The return value is the number of bytes sent.
s.close() Closes the socket
s.getpeername() Returns the remote address of the connected socket. The return value is usually a tuple (ipaddr, port).
s.getsockname() Returns the socket's own address. Usually a tuple (ipaddr, port)
s.setsockopt(level,optname,value) Sets the value of the given socket option.
s.getsockopt(level,optname[.buflen]) Returns the value of the socket option.
s.settimeout(timeout) Sets the timeout period for socket operations. timeout is a float number in seconds. A value of None means no timeout period. Generally, the timeout period should be set when the socket is just created, because they may be used for connection operations (such as connect())
s.gettimeout() Returns the current timeout value in seconds; if no timeout period is set, returns None.
s.fileno() Returns the file descriptor of the socket.
s.setblocking(flag) If flag is False, sets the socket to non-blocking mode; otherwise, sets the socket to blocking mode (the default). In non-blocking mode, if recv() finds no data, or send() cannot send data immediately, a socket.error exception will be raised.
s.makefile() Creates 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 theconnectionobject, indicating that it has connected to the client.

The complete code is as follows:

Example

#!/usr/bin/python3
# File name: server.py

# Import socket, sys modules
import socket
import sys

# Create a socket object
serversocket = socket.socket(
            socket.AF_INET, socket.SOCK_STREAM)

# Get the local hostname
host = socket.gethostname()

port = 9999

# Bind to the port number
serversocket.bind((host, port))

# Set the maximum number of connections; queue beyond that
serversocket.listen(5)

while True:
    # Establish client connection
    clientsocket,addr = serversocket.accept()      

    print("Connection address: %s" % str(addr))
   
    msg='Welcome to Example Tutorial!'+ "\r\n"
    clientsocket.send(msg.encode('utf-8'))
    clientsocket.close()

Client

Next, let's write a simple client example to connect to the service created above. The port number is 9999.

socket.connect(hostname, port )method opens a TCP connection to the hosthostnameportportConnect to the service. After connecting, we can get data from the server. Remember, you need to close the connection after the operation is complete.

The complete code is as follows:

Example

#!/usr/bin/python3
# File name: client.py

# Import socket, sys modules
import socket
import sys

# Create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Get the local hostname
host = socket.gethostname()

# Set the port number
port = 9999

# Connect to the service, specifying host and port
s.connect((host, port))

# Receive data smaller than 1024 bytes
msg = s.recv(1024)

s.close()

print (msg.decode('utf-8'))

Now let's open two terminals. In the first terminal, run the server.py file:

$ python3 server.py

In the second terminal, run the client.py file:

$ python3 client.py 
欢迎访问Example!

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

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

Python Internet Modules

The following lists some important modules for Python network programming:

ProtocolFunction/PurposePort numberPython Module
HTTPWeb access80httplib, urllib, xmlrpclib
NNTPReading and posting news articles, commonly known as "posts"119nntplib
FTPFile transfer20ftplib, urllib
SMTPSending email25smtplib
POP3Receiving email110poplib
IMAP4Fetching email143imaplib
TelnetCommand line23telnetlib
GopherInformation lookup70gopherlib, urllib

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

Other extensions