socket

import socket
Added in v3.0 · Updated March 13, 2026 · Modules
stdlib networking tcp udp ip server client

The socket module is Python’s interface to the BSD socket API, available on all modern Unix systems, Windows, macOS, and most other platforms. It provides the foundation for network communication in Python, enabling you to create both TCP clients and servers, UDP datagram communication, and more specialized socket types.

The module exposes socket families (like AF_INET for IPv4 and AF_UNIX for Unix domain sockets), socket types (SOCK_STREAM for TCP and SOCK_DGRAM for UDP), and functions to create and manipulate sockets. The socket() function returns a socket object whose methods implement the various socket system calls.

Creating Sockets

socket()

The primary function for creating sockets. Returns a new socket object using the specified address family, socket type, and protocol.

socket.socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None)

Parameters:

ParameterTypeDefaultDescription
familyintAF_INETAddress family (e.g., AF_INET, AF_INET6, AF_UNIX)
typeintSOCK_STREAMSocket type (SOCK_STREAM for TCP, SOCK_DGRAM for UDP)
protoint0Protocol number (usually zero, auto-selected)
filenointNoneExisting file descriptor to wrap (auto-detects family/type/proto)

Returns: A socket.socket object.

socketpair()

Creates a pair of connected socket objects. Useful for inter-process communication or testing.

socket.socketpair(family=None, type=SOCK_STREAM, proto=0)

Parameters:

ParameterTypeDefaultDescription
familyintAF_UNIX (or AF_INET if unavailable)Address family for the sockets
typeintSOCK_STREAMSocket type
protoint0Protocol number

Returns: A tuple of two connected socket.socket objects.

create_server()

Creates a server socket bound to an address. A convenience function introduced in Python 3.8 that simplifies the common pattern of creating a listening TCP socket.

socket.create_server(address, *, family=AF_INET, backlog=None, reuse_port=False, dualstack_ipv6=False)

Parameters:

ParameterTypeDefaultDescription
addresstupleA 2-tuple (host, port) to bind to
familyintAF_INETAddress family (AF_INET or AF_INET6)
backlogintNoneQueue size for listen() (system default if None)
reuse_portboolFalseEnable SO_REUSEPORT option
dualstack_ipv6boolFalseAccept both IPv4 and IPv6 connections on IPv6 sockets

Returns: A socket.socket object bound to the address and ready to accept connections.

fromfd()

Creates a socket object from an existing file descriptor.

socket.fromfd(fd, family, type, proto=0)

Parameters:

ParameterTypeDefaultDescription
fdintOpen file descriptor to wrap
familyintAddress family
typeintSocket type
protoint0Protocol number

Returns: A socket.socket object wrapping the file descriptor.

Timeout Functions

setdefaulttimeout()

Sets the default timeout for newly created socket objects.

socket.setdefaulttimeout(timeout)

Parameters:

ParameterTypeDefaultDescription
timeoutfloatTimeout in seconds (None for no timeout)

getdefaulttimeout()

Returns the current default timeout for new socket objects.

socket.getdefaulttimeout()

Returns: The default timeout in seconds as a float, or None if no timeout is set.

Address Families

ConstantDescription
AF_INETIPv4 addresses (host, port) pairs
AF_INET6IPv6 addresses (host, port, flowinfo, scope_id) tuples
AF_UNIXUnix domain sockets (file system paths)
AF_CANController Area Network (Linux)
AF_PACKETRaw packet interface (Linux)

Socket Types

ConstantDescription
SOCK_STREAMOriented to reliable TCP connections
SOCK_DGRAMDatagram-oriented UDP connections
SOCK_RAWRaw socket (bypasses protocol layers)
SOCK_SEQPACKETSequenced packet socket

Examples

TCP server with create_server()

import socket

with socket.create_server(('0.0.0.0', 9000), backlog=5) as server:
    print("Server listening on port 9000")
    conn, addr = server.accept()
    print(f"Connection from {addr}")
    data = conn.recv(1024)
    print(f"Received: {data}")
    conn.sendall(b"Hello from server")
    conn.close()
Server listening on port 9000
Connection from ('127.0.0.1', 54321)
Received: b'Hello client'

Using socketpair() for inter-process communication

import socket

# Create a connected pair of sockets
client, server = socket.socketpair()

# Send data from client to server
client.send(b"Hello from the other end!")
data = server.recv(1024)
print(f"Server received: {data}")

# Clean up
client.close()
server.close()
Server received: b'Hello from the other end!'

UDP datagram socket

import socket

# Create a UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('127.0.0.1', 9001))

# Receive a datagram
data, addr = sock.recvfrom(1024)
print(f"Received from {addr}: {data}")

# Send a response
sock.sendto(b"Ack: " + data, addr)
sock.close()
Received from ('127.0.0.1', 54322): b'Test message'

Common Patterns

Setting a timeout on individual sockets

import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5.0)  # 5 second timeout
sock.connect(('example.com', 80))

Using getdefaulttimeout() for consistent behavior

import socket

# Set default timeout for all new sockets
socket.setdefaulttimeout(10.0)

# Now all new sockets inherit this timeout
sock1 = socket.socket()  # has 10s timeout
sock2 = socket.socket()  # also has 10s timeout

Reusing addresses with SO_REUSEPORT

import socket

# Using create_server with reuse_port
server = socket.create_server(
    ('0.0.0.0', 8000),
    reuse_port=True
)

Errors

The socket module raises several exceptions for different error conditions:

  • socket.error — Deprecated alias for OSError. Raised for general socket errors (e.g., connection refused, network unreachable).

  • socket.timeout — Deprecated alias for TimeoutError. Raised when a socket operation times out.

  • socket.gaierror — Subclass of OSError. Raised for DNS-related errors from getaddrinfo() and getnameinfo().

  • socket.herror — Subclass of OSError. Raised for host-related errors from gethostbyname() and gethostbyaddr().

All socket-related errors are subclasses of OSError, so you can catch them with a single except OSError clause.

See Also