Skip to content

socket

The Python socket module provides a low-level networking interface that allows you to create and use sockets for network communication.

It enables Python programs to connect to other computers over a network, send and receive data, and handle network-related tasks like client-server communication.

Here’s a quick example:

Language: Python
>>> import socket

>>> with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
...     s.connect(("www.example.com", 80))
...

Key Features

  • Creates TCP/IP and UDP sockets
  • Supports both IPv4 and IPv6 addresses
  • Supports blocking, non-blocking, and timeout-based socket operations
  • Includes convenience helpers like create_connection() and create_server() for common client and server setups

Frequently Used Classes and Functions

Object Type Description
socket.socket() Class Represents a network socket
socket.gethostbyname() Function Resolves a hostname to an IPv4 address
socket.getaddrinfo() Function Resolves a host and port into address tuples for IPv4 and IPv6
socket.bind() Method Binds a socket to a local address
socket.listen() Method Enables a socket to accept incoming connections
socket.accept() Method Accepts a connection from a client
socket.recv() Method Receives data from a connected socket
socket.send() Method Sends data to a connected socket
socket.close() Method Closes the socket

Examples

Creating a TCP/IP socket:

Language: Python
>>> import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

Connecting to a server:

Language: Python
>>> s.connect(("www.example.com", 80))

Common Use Cases

  • Creating client-server applications
  • Implementing network protocols
  • Sending and receiving data over TCP/IP and UDP
  • Building web servers or clients
  • Developing chat applications

Real-World Example

Here’s how to create a TCP server that listens for incoming connections and sends a welcome message to the client:

Language: Python Filename: server.py
import socket
import threading

def handle_client(conn, addr):
    with conn:
        print(f"Connected by {addr}")
        conn.sendall(b"Welcome to the server!")

def main():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind(("localhost", 12345))
        s.listen()
        print("Server listening on port 12345...")
        while True:
            conn, addr = s.accept()
            thread = threading.Thread(
                target=handle_client, args=(conn, addr), daemon=True
            )
            thread.start()

if __name__ == "__main__":
    main()

In this example, you use the socket module to create a server that listens on a specified port and sends a welcome message to each client that connects. To try it out, run the script on your computer. You’ll get a message telling you that the server is listening on port 12345. Then, run the following command:

Language: Shell
$ nc localhost 12345
Welcome to the server!
Python Socket Programming

Tutorial

Socket Programming in Python (Guide)

Build a Python socket server and client from scratch, then extend it to handle multiple connections at once without blocking.

advanced python stdlib web-dev

For additional information on related topics, take a look at the following resources:

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Leodanis Pozo Ramos • Updated Oct. 16, 2026