Python Tutorial (35) - Network Programming

Time: Column:Python views:248

Python Provides Two Levels of Network Services

1. Low-Level Network Services

Python offers basic Socket support, providing access to the full set of BSD Sockets API methods for interacting with the underlying operating system's socket interface.

2. High-Level Network Services

The higher-level SocketServer module simplifies the development of network servers by providing server-centric classes.


What is a Socket?

A Socket is essentially a communication endpoint. Applications use sockets to either make requests over the network or respond to requests, enabling communication between processes on the same machine or across different hosts.


socket() Function

In Python, we create a socket using the socket() function. The syntax is as follows:

socket.socket([family[, type[, proto]]])
  • family: The socket family can be either AF_UNIX or AF_INET.

  • type: The socket type can be either SOCK_STREAM (for connection-oriented protocols) or SOCK_DGRAM (for connectionless protocols).

  • proto: The protocol number is generally set to 0 by default.


Socket Object Methods

Server-Side Socket Methods

MethodDescription
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. backlog specifies the maximum number of queued connections. A value of at least 1 is recommended, with most applications using 5.
s.accept()Accepts a TCP client connection (blocking), waiting for an incoming connection.

Client-Side Socket Methods

MethodDescription
s.connect()Actively initiates a TCP server connection. The address is typically in the form of a tuple (hostname, port). If an error occurs, a socket.error exception is raised.
s.connect_ex()An extended version of connect(). Instead of raising an exception on error, it returns an error code.

General Socket Methods

MethodDescription
s.recv()Receives TCP data as a string. bufsize specifies the maximum amount of data to receive.
s.send()Sends TCP data. The data is sent as a string. The return value is the number of bytes sent.
s.sendall()Sends all TCP data. Unlike s.send(), it ensures all data is sent before returning.
s.recvfrom()Receives UDP data. Returns a tuple (data, address) where data is the received string and address is the socket address.
s.sendto()Sends UDP data to the specified remote address in the form of a tuple (ipaddr, port).
s.close()Closes the socket.
s.getpeername()Returns the remote address as a tuple (ipaddr, port) for the connected socket.
s.getsockname()Returns the local address of the socket as a tuple (ipaddr, port).
s.setsockopt()Sets the socket options for a given option name.
s.getsockopt()Returns the value of the socket option.
s.settimeout()Sets the socket timeout value, where timeout is a float value representing seconds. A None value means no timeout is set.
s.gettimeout()Returns the current timeout value. If no timeout is set, None is returned.
s.fileno()Returns the socket’s file descriptor.
s.setblocking()Sets the socket’s blocking mode. If the flag is False, the socket is set to non-blocking mode.
s.makefile()Creates a file object associated with the socket.

Example: Server

In the example below, we use the socket module to create a simple server.

#!/usr/bin/python3
# Filename: server.py

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 the socket to the port
serversocket.bind((host, port))

# Start listening for connections (max 5 connections)
serversocket.listen(5)

while True:
    # Establish a connection with the client
    clientsocket, addr = serversocket.accept()
    
    print("Connection from: %s" % str(addr))
    
    msg = 'Welcome to PMeve!\r\n'
    clientsocket.send(msg.encode('utf-8'))
    clientsocket.close()

Example: Client

Here is a simple client that connects to the server created above.

#!/usr/bin/python3
# Filename: client.py

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 server
s.connect((host, port))

# Receive up to 1024 bytes of data
msg = s.recv(1024)

# Close the connection
s.close()

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

Running the Server and Client

  1. In the first terminal, run the server script:

    $ python3 server.py
  2. In a second terminal, run the client script:

    $ python3 client.py

You should see the following message in the client terminal:

Welcome to PMeve!

On the server side, the terminal will output:

Connection from: ('192.168.0.118', 33397)

Python Internet Modules

The table below lists some important Python modules for network programming:

ProtocolPurposePort NumberPython Module
HTTPWeb page access80httplib, urllib, xmlrpclib
NNTPPosting and reading news articles119nntplib
FTPFile transfer20ftplib, urllib
SMTPSending emails25smtplib
POP3Receiving emails110poplib
IMAP4Fetching emails143imaplib
TelnetCommand-line interface23telnetlib
GopherInformation search70gopherlib, urllib