# pydoc > socket

---
type: CommandReference
command: socket
mode: pydoc
section: 
source: pydoc3
---

## Quick Reference

- `s = socket.socket(family=AF_INET, type=SOCK_STREAM)` — create a TCP socket
- `s.connect(('host', port))` — connect to a remote address
- `s.send(data)` — send data (returns bytes sent)
- `s.recv(bufsize)` — receive data
- `s.bind(('localhost', port))` — bind to local address
- `s.listen([backlog])` — listen for connections
- `conn, addr = s.accept()` — accept a connection
- `socket.create_connection(('host', port))` — convenience function to connect
- `socket.getaddrinfo('host', port)` — resolve host and port to address info

## Name

This module provides socket operations and some related functions. On Unix, it supports IP and Unix domain sockets; on other systems, only IP.

## Synopsis

python
import socket
s = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0)
# or using fileno:
s = socket.socket(fileno=fd)
## Functions

- `socket.socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None)` — create a new socket object. If `fileno` is given, `family`, `type`, and `proto` are auto-detected unless explicitly set. The socket is created as non-inheritable.
- `socket.socketpair([family[, type[, proto]]])` — create a pair of connected socket objects. Default family is `AF_UNIX` if defined, else `AF_INET`.
- `socket.fromfd(fd, family, type[, proto])` — create a socket object from a duplicate of the given file descriptor.
- `socket.send_fds(sock, buffers, fds[, flags[, address]])` — send file descriptors over an `AF_UNIX` socket.
- `socket.recv_fds(sock, bufsize, maxfds[, flags])` — receive file descriptors over an `AF_UNIX` socket.
- `socket.gethostname()` — return the current host name.
- `socket.gethostbyname(host)` — return the IP address string for a host.
- `socket.gethostbyname_ex(host)` — return `(name, aliaslist, addresslist)`.
- `socket.gethostbyaddr(host)` — return `(name, aliaslist, addresslist)`.
- `socket.getservbyname(servicename[, protocolname])` — return port number from service name.
- `socket.getservbyport(port[, protocolname])` — return service name from port number.
- `socket.getprotobyname(name)` — return protocol number for the named protocol.
- `socket.ntohl(integer)` — convert 32-bit integer from network to host byte order.
- `socket.ntohs(integer)` — convert 16-bit unsigned integer from network to host byte order.
- `socket.htonl(integer)` — convert 32-bit integer from host to network byte order.
- `socket.htons(integer)` — convert 16-bit unsigned integer from host to network byte order.
- `socket.inet_aton(string)` — convert dotted-quad string to 32-bit packed bytes.
- `socket.inet_ntoa(packed_ip)` — convert 32-bit packed bytes to dotted-quad string.
- `socket.inet_pton(af, ip)` — convert IP address string to packed bytes for given address family.
- `socket.inet_ntop(af, packed_ip)` — convert packed IP address bytes to string format.
- `socket.getaddrinfo(host, port, family=0, type=0, proto=0, flags=0)` — resolve host/port into list of address info tuples.
- `socket.getnameinfo(sockaddr, flags)` — return `(host, port)` for a sockaddr.
- `socket.getdefaulttimeout()` — return the default timeout in seconds (float) for new socket objects, or `None`.
- `socket.setdefaulttimeout(timeout)` — set default timeout in seconds for new socket objects.
- `socket.create_connection(address, timeout=None, source_address=None)` — connect to `(host, port)` and return the socket object.
- `socket.create_server(address, family=AF_INET, backlog=None, reuse_port=False, dualstack_ipv6=False)` — create a listening TCP socket bound to `(host, port)`.
- `socket.has_dualstack_ipv6()` — return `True` if platform supports dual-stack IPv6 sockets.
- `socket.if_nametoindex(if_name)` — return interface index for given interface name.
- `socket.if_indextoname(if_index)` — return interface name for given index.
- `socket.if_nameindex()` — return list of `(index, name)` tuples for network interfaces.
- `socket.sethostname(name)` — set the hostname (Unix only).
- `socket.close(fd)` — close an integer socket file descriptor.
- `socket.dup(fd)` — duplicate an integer socket file descriptor.
- `socket.CMSG_LEN(length)` — return total length of ancillary data item with given data length (without padding).
- `socket.CMSG_SPACE(length)` — return buffer size needed for `recvmsg()` to receive ancillary data item with given data length (including padding).

## Classes

### `socket.socket` (inherits from `_socket.socket`)

A socket object representing one endpoint of a network connection.

**Constructor**: `socket(family=-1, type=-1, proto=-1, fileno=None)`

**Methods** (keyword arguments not allowed except where noted):
- `accept()` — wait for an incoming connection, return `(socket object, address)`.
- `bind(address)` — bind to a local address (e.g., `(host, port)`).
- `close()` — close the socket.
- `connect(address)` — connect to a remote address.
- `connect_ex(address)` — connect, return error code instead of raising exception.
- `detach()` — close socket object without closing underlying file descriptor; return fd.
- `dup()` — duplicate the socket, return new socket object (non-inheritable).
- `fileno()` — return integer file descriptor.
- `getblocking()` — return `True` if socket is blocking.
- `getpeername()` — return remote address (e.g., `(hostaddr, port)`).
- `getsockname()` — return local address.
- `getsockopt(level, option[, buffersize])` — get socket option.
- `gettimeout()` — return timeout in seconds, or `None`.
- `listen([backlog])` — start listening for connections.
- `makefile(mode='r', buffering=None, ...)` — return an I/O stream connected to the socket.
- `recv(buffersize[, flags])` — receive up to `buffersize` bytes.
- `recv_into(buffer, [nbytes[, flags]])` — receive data into a buffer.
- `recvfrom(buffersize[, flags])` — receive data and sender's address.
- `recvfrom_into(buffer[, nbytes[, flags]])` — receive data into buffer + address.
- `recvmsg(bufsize[, ancbufsize[, flags]])` — receive data and ancillary data, returns `(data, ancdata, msg_flags, address)`.
- `recvmsg_into(buffers[, ancbufsize[, flags]])` — scatter receive into buffers.
- `send(data[, flags])` — send data, returns number of bytes sent.
- `sendall(data[, flags])` — send all data, repeats `send()` until done.
- `sendmsg(buffers[, ancdata[, flags[, address]]])` — send normal and ancillary data.
- `sendmsg_afalg([msg], *, op[, iv[, assoclen[, flags=MSG_MORE]]])` — set operation mode for AF_ALG socket.
- `sendto(data[, flags], address)` — send data to a specific address.
- `sendfile(file, offset=0, count=None)` — send a file using `os.sendfile()`.
- `setblocking(flag)` — set blocking (`True`) or non-blocking (`False`).
- `setsockopt(level, option, value)` — set socket option.
- `settimeout(timeout)` — set timeout on socket operations (float or `None`).
- `shutdown(how)` — shut down reading (`SHUT_RD`), writing (`SHUT_WR`), or both (`SHUT_RDWR`).
- `get_inheritable()` / `set_inheritable(inheritable)` — get/set inheritable flag.

**Data descriptors**: `family` (address family), `type` (socket type), `proto` (protocol), `timeout` (timeout).

### `socket.AddressFamily` (enum.IntEnum)

Address families:
- `AF_UNIX` (1), `AF_INET` (2), `AF_AX25` (3), `AF_IPX` (4), `AF_APPLETALK` (5), `AF_NETROM` (6), `AF_BRIDGE` (7), `AF_ATMPVC` (8), `AF_X25` (9), `AF_INET6` (10), `AF_ROSE` (11), `AF_DECnet` (12), `AF_NETBEUI` (13), `AF_SECURITY` (14), `AF_KEY` (15), `AF_NETLINK` (16), `AF_PACKET` (17), `AF_ASH` (18), `AF_ECONET` (19), `AF_ATMSVC` (20), `AF_RDS` (21), `AF_SNA` (22), `AF_IRDA` (23), `AF_PPPOX` (24), `AF_WANPIPE` (25), `AF_LLC` (26), `AF_CAN` (29), `AF_TIPC` (30), `AF_BLUETOOTH` (31), `AF_ALG` (38), `AF_VSOCK` (40), `AF_QIPCRTR` (42), `AF_UNSPEC` (0).

### `socket.SocketKind` (enum.IntEnum)

Socket types:
- `SOCK_STREAM` (1), `SOCK_DGRAM` (2), `SOCK_RAW` (3), `SOCK_RDM` (4), `SOCK_SEQPACKET` (5), `SOCK_CLOEXEC` (524288), `SOCK_NONBLOCK` (2048).

### `socket.error` (alias for `OSError`)

Base class for I/O related errors. Subclasses include `BlockingIOError`, `ChildProcessError`, `ConnectionError`, etc.

### `socket.gaierror` (inherits `OSError`)

Raised for getaddrinfo/getnameinfo errors.

### `socket.herror` (inherits `OSError`)

Raised for hostname resolution errors.

### `socket.timeout` (alias for `TimeoutError`, inherits `OSError`)

Raised when a socket operation times out.

## Important Constants

- `AF_INET`, `AF_INET6`, `AF_UNIX`, `AF_UNSPEC` — address families
- `SOCK_STREAM`, `SOCK_DGRAM`, `SOCK_RAW`, `SOCK_RDM`, `SOCK_SEQPACKET` — socket types
- `SHUT_RD` (0), `SHUT_WR` (1), `SHUT_RDWR` (2) — shutdown modes
- `SOL_SOCKET` (1), `SOL_TCP` (6), `SOL_UDP` (17), `SOL_IP` (0) — protocol levels
- `SO_REUSEADDR` (2), `SO_KEEPALIVE` (9), `SO_LINGER` (13), `SO_BROADCAST` (6), `SO_RCVBUF` (8), `SO_SNDBUF` (7), `SO_ERROR` (4), `SO_TYPE` (3) — socket options
- `IPPROTO_TCP` (6), `IPPROTO_UDP` (17), `IPPROTO_ICMP` (1), `IPPROTO_IP` (0) — IP protocols
- `TCP_NODELAY` (1), `TCP_CORK` (3), `TCP_KEEPIDLE` (4), `TCP_KEEPINTVL` (5), `TCP_KEEPCNT` (6) — TCP options
- `MSG_PEEK` (2), `MSG_OOB` (1), `MSG_DONTWAIT` (64), `MSG_WAITALL` (256), `MSG_NOSIGNAL` (16384) — send/recv flags
- `INADDR_ANY` (0), `INADDR_LOOPBACK` (2130706433), `INADDR_BROADCAST` (4294967295) — special IPv4 addresses
- `IPV6_V6ONLY` (26), `IPV6_MULTICAST_HOPS` (18), `IPV6_JOIN_GROUP` (20), `IPV6_LEAVE_GROUP` (21) — IPv6 options
- `SOMAXCONN` (4096) — maximum backlog for listen()
- `has_ipv6` — boolean indicating if IPv6 is supported

## See Also

- [Python Documentation: socket — Low-level networking interface](https://docs.python.org/3.10/library/socket.html)
- Unix manual pages: `socket(2)`, `bind(2)`, `connect(2)`, `listen(2)`, `accept(2)`, `send(2)`, `recv(2)`, `setsockopt(2)`, `getsockopt(2)`, `getaddrinfo(3)`