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:

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
  • Provides functions for both synchronous and asynchronous network communication
  • Offers high-level interfaces for creating server and client applications

Frequently Used Classes and Functions

Object Type Description
socket.socket() Class Represents a network socket
socket.gethostbyname() Function Resolves a hostname to an IP address
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:

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

Connecting to a server:

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:

Python 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:

Shell
$ nc localhost 12345
Welcome to the server!