Python3 Network Programming
Python provides two levels of access to network services:
Low-level network services support basic Socket, which provides the standard BSD Sockets API and allows access to all methods of the underlying operating system's Socket interface.
High-level network services module SocketServer, which provides server-centric classes to simplify the development of network servers.
What is a Socket?
A Socket, also known as a "socket", is typically used by applications to send requests or respond to network requests, enabling communication between hosts or 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 either
SOCK_STREAM
for connection-oriented protocols orSOCK_DGRAM
for connectionless protocols.proto: Usually defaults to 0 if not specified.
Socket Object (Built-in) Methods
Function | Description |
---|---|
Server-side Socket | |
s.bind() | Binds the address (host, port) to the socket. For AF_INET, the address is represented as a tuple (host, port). |
s.listen() | Starts TCP listening. The backlog specifies the maximum number of connections the operating system can queue before rejecting new ones. This value should be at least 1, and 5 is commonly used. |
s.accept() | Passively accepts a TCP client connection, waiting until the connection arrives (blocking). |
Client-side Socket | |
s.connect() | Actively initializes a TCP server connection. The address format is typically a tuple (hostname, port). If the connection fails, a socket.error is returned. |
s.connect_ex() | An extended version of the connect() function that returns an error code instead of raising an exception on failure. |
Common Socket Functions | |
s.recv() | Receives TCP data. The data is returned as a string, with bufsize specifying the maximum amount of data to be received. The flag provides additional information about the message and is usually ignored. |
s.send() | Sends TCP data, sending the data in the string to the connected socket. The return value is the number of bytes sent, which may be less than the size of the string. |
s.sendall() | Sends all TCP data. It attempts to send all data in the string to the connected socket before returning. Success returns None; failure raises an exception. |
s.recvfrom() | Receives UDP data, similar to recv() but returns a tuple (data, address), where data is the received data string and address is the socket address of the sender. |
s.sendto() | Sends UDP data, sending the data to the socket with the address specified as a tuple (ipaddr, port). 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 address of the socket itself. Typically a tuple (ipaddr, port). |
s.setsockopt(level, optname, value) | Sets the value of the specified socket option. |
s.getsockopt(level, optname[, buflen]) | Returns the value of the socket option. |
s.settimeout(timeout) | Sets the timeout for socket operations, with timeout being a float in seconds. A value of None means no timeout. Timeouts should usually be set when the socket is first created, as they may apply to connection operations like connect(). |
s.gettimeout() | Returns the current timeout value in seconds, or None if no timeout is set. |
s.fileno() | Returns the file descriptor of the socket. |
s.setblocking(flag) | If flag is False, sets the socket to non-blocking mode; otherwise, it sets it to blocking mode (default). In non-blocking mode, if recv() finds no data or send() cannot send data immediately, a socket.error exception is raised. |
s.makefile() | Creates a file associated with the socket. |
Simple Example
Server
We use the socket function from the socket module to create a socket object. The socket object can then be configured to set up a socket service by calling other functions. We can now specify the service port by calling the bind(hostname, port) function.
Next, we call the accept method of the socket object. This method waits for a client connection and returns a connection object, representing the connection to the client.
Here is the complete code:
Example
#!/usr/bin/python3
# File name: server.py
# Import socket and sys modules
import socket
import sys
# Create a socket object
serversocket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
# Get local hostname
host = socket.gethostname()
port = 9999
# Bind to the port
serversocket.bind((host, port))
# Set the maximum number of queued connections
serversocket.listen(5)
while True:
# Establish a client connection
clientsocket,addr = serversocket.accept()
print("Connection address: %s" % str(addr))
msg='Welcome to tutorialpro.org!'+ "\r\n"
clientsocket.send(msg.encode('utf-8'))
clientsocket.close()
Client
Next, we write a simple client example to connect to the server created above. The port number is 9999.
The socket.connect(hostname, port) method opens a TCP connection to the provider with the hostname hostname and port port. After connecting, we can retrieve data from the server. Remember to close the connection after the operation is complete.
Here is the complete code:
Example
#!/usr/bin/python3
# File name: client.py
# Import socket and sys modules
import socket
import sys
# Create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Get local hostname
host = socket.gethostname()
# Set the port number
port = 9999
# Connect to the server, specifying the host and port
s.connect((host, port))
# Receive data of less than 1024 bytes
msg = s.recv(1024)
s.close()
print (msg.decode('utf-8'))
Now, open two terminals. In the first terminal, execute the server.py file:
$ python3 server.py
In the second terminal, execute the client.py file:
$ python3 client.py
Welcome to tutorialpro.org!
If you then open the first terminal again, you will see the following output:
Connection address: ('192.168.0.118', 33397)
Python Internet Modules
The following table lists some important Python modules for network programming:
Protocol | Function | Port | Python Module |
---|---|---|---|
HTTP | Web access | 80 | httplib, urllib, xmlrpclib |
NNTP | Reading and posting news articles, commonly known as "posts" | 119 | nntplib |
FTP | File transfer | 20 | ftplib, urllib |
SMTP | Sending emails | 25 | smtplib |
POP3 | Receiving emails | 110 | poplib |
IMAP4 | Retrieving emails | 143 | imaplib |
Telnet | Command line | 23 | telnetlib |
Gopher | Information lookup | 70 | gopherlib, urllib |
For more information, refer to the Python Socket Library and Modules on the official website.