Skip to content

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 can access all methods of the underlying operating system Socket interface.
  • High-level network service module SocketServer, which provides server-centric classes that can simplify the development of network servers.

Socket is also known as a “socket”. Applications typically use “sockets” to send requests to or respond to network requests, enabling communication between hosts or between processes on a single computer.


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

socket.socket([family[, type[, proto]]])
  • family: The socket family can be AF_UNIX or AF_INET
  • type: The socket type can be SOCK_STREAM or SOCK_DGRAM depending on whether it is connection-oriented or connectionless
  • proto: Generally not filled in, defaults to 0.
Function Description
Server-side Socket
s.bind() Bind address (host, port) to the socket. Under AF_INET, the address is represented as 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 should be at least 1; most applications set it to 5.
s.accept() Passively accept TCP client connections, (blocking) wait for incoming connections
Client-side Socket
s.connect() Actively initialize a TCP server connection. The address format is generally 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 instead of raising an exception when an error occurs.
General-purpose Socket Functions
s.recv() Receive TCP data. 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 to send, which may be less than the byte size of the 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, raises an exception on failure.
s.recvfrom() Receive UDP data. Similar to recv(), but the return value is (data, address). Where data is the string containing the received data, and address is the socket address of the sender.
s.sendto() Send UDP data. Sends data to the socket. address is a tuple of the form (ipaddr, port) specifying the remote address. The return value is the number of bytes sent.
s.close() Close the socket
s.getpeername() Returns the remote address of the connected socket. The return value is typically a tuple (ipaddr, port).
s.getsockname() Returns the socket’s own address. Typically a tuple (ipaddr, port)
s.setsockopt(level,optname,value) Set the value of a given socket option.
s.getsockopt(level,optname[.buflen]) Returns the value of a 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. Generally, the timeout should be set right after creating the socket, as it may be used for connection operations (such as connect())
s.gettimeout() Returns the current timeout value in seconds. If no timeout is set, returns None.
s.fileno() Returns the file descriptor of the socket.
s.setblocking(flag) If flag is False, 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, a socket.error exception will be raised.
s.makefile() Create a file associated with the socket

We use the socket module’s socket function to create a socket object. The socket object can be used to set up a socket service by calling other functions.

Now we can specify the service’s port by calling the bind(hostname, port) function.

Next, we call the socket object’s accept method. This method waits for client connections and returns a connection object, indicating that it is connected to the client.

The complete code is as follows:

#!/usr/bin/python3
# Filename: 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 the port number
serversocket.bind((host, port))

# Set the maximum number of connections, queue after exceeding
serversocket.listen(5)

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

    print("Connection address: %s" % str(addr))

    msg='Welcome to Runoob Tutorial!'+ "\r\n"
    clientsocket.send(msg.encode('utf-8'))
    clientsocket.close()

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

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

The complete code is as follows:

#!/usr/bin/python3
# Filename: 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 the host and port
s.connect((host, port))

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

s.close()

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

Now we open two terminals. The first terminal runs the server.py file:

$ python3 server.py

The second terminal runs the client.py file:

$ python3 client.py
Welcome to Runoob Tutorial!

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

Connection address: ('192.168.0.118', 33397)

The following lists some important modules for Python network programming:

Protocol Function/Uses Port Python Module
HTTP Web page 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 email 25 smtplib
POP3 Receiving email 110 poplib
IMAP4 Fetching email 143 imaplib
Telnet Command line 23 telnetlib
Gopher Information lookup 70 gopherlib, urllib

For more content, please refer to the official Python Socket Library and Modules.