🔗

Overview of Python Socket Library

May 12, 2025

Python Socket Library Overview

Introduction

  • Provides access to BSD socket interface.
  • Available on Unix, Windows, MacOS.
  • Python interface mirrors Unix system call and library interface with an object-oriented style.

Socket Families

  • AF_UNIX: Address bound to a file system node, represented as a string.
  • AF_INET: Uses a pair (host, port), supports IPv4.
  • AF_INET6: Uses a four-tuple (host, port, flowinfo, scope_id), supports IPv6.
  • AF_NETLINK, AF_TIPC, AF_CAN, AF_ALG, AF_VSOCK, AF_PACKET: Various address families for specific use cases.
  • AF_BLUETOOTH, AF_HYPERV: Specialized for Bluetooth and Hyper-V communication.
  • IPPROTO_UDPLITE: Allows specification of packet coverage for checksum.

Error Handling

  • Errors raise exceptions such as OSError or its subclasses.
  • Non-blocking mode supported via setblocking(), timeouts via settimeout().

Key Constants

  • Address Family Constants: e.g., socket.AF_INET, socket.AF_INET6.
  • Socket Type Constants: e.g., socket.SOCK_STREAM, socket.SOCK_DGRAM.
  • Miscellaneous Constants: Various constants like SO_REUSEADDR for socket options.

Functions

Creating Sockets

  • socket.socket(): Creates a new socket with specified family, type, and protocol.
  • socket.socketpair(): Builds a pair of connected socket objects.
  • socket.create_connection(): Connects to a TCP service.
  • socket.create_server(): Creates a TCP socket server.
  • socket.fromfd() and socket.fromshare(): Create sockets from file descriptors or shared data.

Other Functions

  • socket.getaddrinfo(): Translates address info.
  • socket.gethostname(), socket.gethostbyname(): Resolves hostnames.
  • socket.inet_pton() and socket.inet_ntop(): IP address conversions.
  • socket.send() and socket.recv(): Sending and receiving data.

Socket Objects

  • Methods correspond to Unix system calls.
  • Key Methods: accept(), bind(), close(), connect(), listen(), recv(), send().
  • Attributes: family, type, proto.

Examples

TCP Echo Server and Client

  • Server: Uses socket(), bind(), listen(), accept().
  • Client: Uses socket(), connect().

Advanced Examples

  • Network sniffer on Windows with raw sockets.
  • Communication with CAN network using raw socket protocol.

Notes

  • Timeouts: Sockets can operate in blocking, non-blocking, or timeout modes.
  • Security: Using SO_REUSEADDR to manage socket reuse in TIME_WAIT state.

References

  • For more detailed study, refer to Unix Programmer’s Manual and specific RFCs for network programming.