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_UNIXor- 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
| Method | Description | 
|---|---|
| s.bind() | Binds the address (host, port)to the socket. ForAF_INET, the address is represented as a tuple(host, port). | 
| s.listen() | Starts TCP listening. backlogspecifies 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
| Method | Description | 
|---|---|
| s.connect() | Actively initiates a TCP server connection. The address is typically in the form of a tuple (hostname, port). If an error occurs, asocket.errorexception 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
| Method | Description | 
|---|---|
| s.recv() | Receives TCP data as a string. bufsizespecifies 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)wheredatais the received string andaddressis 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 timeoutis a float value representing seconds. ANonevalue means no timeout is set. | 
| s.gettimeout() | Returns the current timeout value. If no timeout is set, Noneis returned. | 
| s.fileno() | Returns the socket’s file descriptor. | 
| s.setblocking() | Sets the socket’s blocking mode. If the flagisFalse, 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
- In the first terminal, run the server script: - $ python3 server.py 
- 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:
| Protocol | Purpose | Port Number | Python Module | 
|---|---|---|---|
| HTTP | Web page access | 80 | httplib,urllib,xmlrpclib | 
| NNTP | Posting and reading news articles | 119 | nntplib | 
| FTP | File transfer | 20 | ftplib,urllib | 
| SMTP | Sending emails | 25 | smtplib | 
| POP3 | Receiving emails | 110 | poplib | 
| IMAP4 | Fetching emails | 143 | imaplib | 
| Telnet | Command-line interface | 23 | telnetlib | 
| Gopher | Information search | 70 | gopherlib,urllib | 
 
  
  
 