2 min read

Python Socket Module

The socket module provides access to the BSD socket interface. It is available on all modern Unix systems, Windows, macOS, and other platforms. It is the foundation for network communication in Python.

Importing the Module

import socket

Socket Families and Types

Address Families

  • socket.AF_INET: IPv4 (default).
  • socket.AF_INET6: IPv6.
  • socket.AF_UNIX: Unix Domain Sockets (local inter-process communication).

Socket Types

  • socket.SOCK_STREAM: TCP (reliable, connection-oriented).
  • socket.SOCK_DGRAM: UDP (unreliable, connectionless).

Creating a Socket

import socket

# Create a TCP/IP socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

Utility Functions

Hostname and IP

# Get the local hostname
hostname = socket.gethostname()
print(f"Hostname: {hostname}")

# Get IP address by hostname
ip_address = socket.gethostbyname(hostname)
print(f"IP Address: {ip_address}")

# Get fully qualified domain name
print(socket.getfqdn('8.8.8.8'))

Service Names

# Get port number for a service
print(socket.getservbyname('http')) # 80
print(socket.getservbyname('ssh'))  # 22

Timeouts

You can set a default timeout for all new sockets or specific timeouts for individual sockets.

# Set default timeout for new sockets (in seconds)
socket.setdefaulttimeout(5)

# Set timeout for a specific socket
s.settimeout(2.0)

Error Handling

Socket operations raise socket.error (an alias for OSError) on failure.

import socket

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(("non-existent-host", 80))
except socket.error as e:
    print(f"Socket error: {e}")

For a full client/server implementation guide, see programming/python/socket-programming.

programming/python/python