Python socket Module

The socket module in Python provides access to the BSD socket interface. It allows you to create networking applications, handle connections, send and receive data over the network, and more.

Table of Contents

  1. Introduction
  2. Key Classes and Functions
    • socket
    • socket.socket
    • socket.bind
    • socket.listen
    • socket.accept
    • socket.connect
    • socket.send
    • socket.recv
    • socket.close
    • socket.gethostbyname
    • socket.gethostname
    • socket.getaddrinfo
  3. Examples
    • Creating a Simple Server
    • Creating a Simple Client
    • Handling Multiple Connections
    • Using Non-Blocking Sockets
    • Resolving Hostnames
  4. Real-World Use Case
  5. Conclusion
  6. References

Introduction

The socket module in Python provides a way to work with network connections and sockets. It supports both TCP and UDP protocols and allows for both blocking and non-blocking operations. This module is essential for building networked applications in Python.

Key Classes and Functions

socket

The socket class provides a way to create and manipulate network sockets.

import socket

socket.socket

Creates a new socket using the given address family, socket type, and protocol number.

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

socket.bind

Binds the socket to an address and port.

s.bind(('localhost', 12345))

socket.listen

Enables the server to accept connections.

s.listen(5)

socket.accept

Accepts a connection. The socket must be bound to an address and listening for connections.

conn, addr = s.accept()

socket.connect

Connects to a remote socket at the given address.

s.connect(('localhost', 12345))

socket.send

Sends data to the socket.

s.send(b'Hello, World!')

socket.recv

Receives data from the socket.

data = s.recv(1024)

socket.close

Closes the socket.

s.close()

socket.gethostbyname

Returns the IP address of a hostname.

ip = socket.gethostbyname('www.example.com')

socket.gethostname

Returns the hostname of the machine.

hostname = socket.gethostname()

socket.getaddrinfo

Translates the host/port argument into a sequence of 5-tuples that contain all the necessary information to create a socket.

addr_info = socket.getaddrinfo('www.example.com', 80)

Examples

Creating a Simple Server

import socket

def server():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('localhost', 12345))
    s.listen(5)
    print('Server listening on port 12345')

    while True:
        conn, addr = s.accept()
        print(f'Connected by {addr}')
        data = conn.recv(1024)
        if not data:
            break
        conn.sendall(data)
        conn.close()

if __name__ == '__main__':
    server()

Creating a Simple Client

import socket

def client():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(('localhost', 12345))
    s.sendall(b'Hello, World!')
    data = s.recv(1024)
    print(f'Received {data}')
    s.close()

if __name__ == '__main__':
    client()

Handling Multiple Connections

import socket
import threading

def handle_client(conn, addr):
    print(f'Connected by {addr}')
    while True:
        data = conn.recv(1024)
        if not data:
            break
        conn.sendall(data)
    conn.close()

def server():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('localhost', 12345))
    s.listen(5)
    print('Server listening on port 12345')

    while True:
        conn, addr = s.accept()
        client_thread = threading.Thread(target=handle_client, args=(conn, addr))
        client_thread.start()

if __name__ == '__main__':
    server()

Using Non-Blocking Sockets

import socket

def non_blocking_server():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('localhost', 12345))
    s.listen(5)
    s.setblocking(False)
    print('Non-blocking server listening on port 12345')

    while True:
        try:
            conn, addr = s.accept()
        except BlockingIOError:
            continue
        print(f'Connected by {addr}')
        data = conn.recv(1024)
        if data:
            conn.sendall(data)
        conn.close()

if __name__ == '__main__':
    non_blocking_server()

Resolving Hostnames

import socket

def resolve_hostname():
    hostname = 'www.example.com'
    ip_address = socket.gethostbyname(hostname)
    print(f'The IP address of {hostname} is {ip_address}')

if __name__ == '__main__':
    resolve_hostname()

Real-World Use Case

Simple Chat Application

import socket
import threading

def handle_client(conn, addr):
    print(f'Connected by {addr}')
    while True:
        try:
            data = conn.recv(1024)
            if not data:
                break
            broadcast(data, conn)
        except:
            break
    conn.close()

def broadcast(message, connection):
    for client in clients:
        if client != connection:
            try:
                client.send(message)
            except:
                client.close()
                clients.remove(client)

def server():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('localhost', 12345))
    s.listen(5)
    print('Chat server listening on port 12345')

    while True:
        conn, addr = s.accept()
        clients.add(conn)
        client_thread = threading.Thread(target=handle_client, args=(conn, addr))
        client_thread.start()

clients = set()

if __name__ == '__main__':
    server()

Client Code:

import socket
import threading

def receive_messages(sock):
    while True:
        try:
            message = sock.recv(1024)
            print(message.decode())
        except:
            break

def client():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(('localhost', 12345))

    threading.Thread(target=receive_messages, args=(sock,)).start()

    while True:
        message = input()
        sock.send(message.encode())

if __name__ == '__main__':
    client()

Conclusion

The socket module in Python provides a powerful and flexible way to create networked applications. It supports both TCP and UDP protocols, blocking and non-blocking operations, and is essential for any application that requires network communication.

References

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top