pydoc > socket

📛 NAME

socket

🚀 Quick Reference

Use CaseCommandDescription
🌐 Create a TCP socketsocket.socket(socket.AF_INET, socket.SOCK_STREAM)Create a new IPv4 TCP socket
🔗 Connect to a remote hosts.connect(('host', port))Connect socket to a remote address
📥 Send datas.sendall(b'data')Send all data reliably
📤 Receive datadata = s.recv(1024)Receive up to 1024 bytes
🖥️ Create a servers.bind(('', 8080)) then s.listen()Bind and listen for incoming connections
🔌 Accept connectionsconn, addr = s.accept()Wait for and accept a new connection
🔍 Resolve hostnamesocket.gethostbyname('example.com')Get IP address from hostname
⏱️ Set timeouts.settimeout(5.0)Set timeout for socket operations (seconds)

📚 MODULE REFERENCE

https://docs.python.org/3.10/library/socket.html

The following documentation is automatically generated from the Python source files. It may be incomplete, incorrect or include features that are considered implementation detail and may vary between Python implementations. When in doubt, consult the module reference at the location listed above.

📝 DESCRIPTION

This module provides socket operations and some related functions. On Unix, it supports IP (Internet Protocol) and Unix domain sockets. On other systems, it only supports IP. Functions specific for a socket are available as methods of the socket object.

🔧 Functions

[*] not available on all platforms!

🎯 Special objects

🔢 IntEnum constants

🔢 Integer constants

Many other constants may be defined; these may be used in calls to the setsockopt() and getsockopt() methods.

🏛️ CLASSES

builtins.Exception(builtins.BaseException)
    builtins.OSError
        builtins.TimeoutError
        gaierror
        herror
builtins.object
    _socket.socket
        socket
enum.IntEnum(builtins.int, enum.Enum)
    AddressFamily
    SocketKind

🏷️ class AddressFamily

class AddressFamily(enum.IntEnum)
 |  AddressFamily(value, names=None, *, module=None, qualname=None, type=None, start=1)
 |
 |  An enumeration.
 |
 |  Method resolution order:
 |      AddressFamily
 |      enum.IntEnum
 |      builtins.int
 |      enum.Enum
 |      builtins.object
 |
 |  Data and other attributes defined here:
 |
 |  AF_ALG = <AddressFamily.AF_ALG: 38>
 |  AF_APPLETALK = <AddressFamily.AF_APPLETALK: 5>
 |  AF_ASH = <AddressFamily.AF_ASH: 18>
 |  AF_ATMPVC = <AddressFamily.AF_ATMPVC: 8>
 |  AF_ATMSVC = <AddressFamily.AF_ATMSVC: 20>
 |  AF_AX25 = <AddressFamily.AF_AX25: 3>
 |  AF_BLUETOOTH = <AddressFamily.AF_BLUETOOTH: 31>
 |  AF_BRIDGE = <AddressFamily.AF_BRIDGE: 7>
 |  AF_CAN = <AddressFamily.AF_CAN: 29>
 |  AF_ECONET = <AddressFamily.AF_ECONET: 19>
 |  AF_INET = <AddressFamily.AF_INET: 2>
 |  AF_INET6 = <AddressFamily.AF_INET6: 10>
 |  AF_IPX = <AddressFamily.AF_IPX: 4>
 |  AF_IRDA = <AddressFamily.AF_IRDA: 23>
 |  AF_KEY = <AddressFamily.AF_KEY: 15>
 |  AF_LLC = <AddressFamily.AF_LLC: 26>
 |  AF_NETBEUI = <AddressFamily.AF_NETBEUI: 13>
 |  AF_NETLINK = <AddressFamily.AF_NETLINK: 16>
 |  AF_NETROM = <AddressFamily.AF_NETROM: 6>
 |  AF_PACKET = <AddressFamily.AF_PACKET: 17>
 |  AF_PPPOX = <AddressFamily.AF_PPPOX: 24>
 |  AF_QIPCRTR = <AddressFamily.AF_QIPCRTR: 42>
 |  AF_RDS = <AddressFamily.AF_RDS: 21>
 |  AF_ROSE = <AddressFamily.AF_ROSE: 11>
 |  AF_SECURITY = <AddressFamily.AF_SECURITY: 14>
 |  AF_SNA = <AddressFamily.AF_SNA: 22>
 |  AF_TIPC = <AddressFamily.AF_TIPC: 30>
 |  AF_UNIX = <AddressFamily.AF_UNIX: 1>
 |  AF_UNSPEC = <AddressFamily.AF_UNSPEC: 0>
 |  AF_VSOCK = <AddressFamily.AF_VSOCK: 40>
 |  AF_WANPIPE = <AddressFamily.AF_WANPIPE: 25>
 |  AF_X25 = <AddressFamily.AF_X25: 9>
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from enum.Enum:
 |
 |  name
 |      The name of the Enum member.
 |
 |  value
 |      The value of the Enum member.
 |
 |  ----------------------------------------------------------------------
 |  Readonly properties inherited from enum.EnumMeta:
 |
 |  __members__
 |      Returns a mapping of member name->value.
 |
 |      This mapping lists all enum members, including aliases. Note that this
 |      is a read-only view of the internal mapping.

🏷️ class SocketKind

class SocketKind(enum.IntEnum)
 |  SocketKind(value, names=None, *, module=None, qualname=None, type=None, start=1)
 |
 |  An enumeration.
 |
 |  Method resolution order:
 |      SocketKind
 |      enum.IntEnum
 |      builtins.int
 |      enum.Enum
 |      builtins.object
 |
 |  Data and other attributes defined here:
 |
 |  SOCK_CLOEXEC = <SocketKind.SOCK_CLOEXEC: 524288>
 |  SOCK_DGRAM = <SocketKind.SOCK_DGRAM: 2>
 |  SOCK_NONBLOCK = <SocketKind.SOCK_NONBLOCK: 2048>
 |  SOCK_RAW = <SocketKind.SOCK_RAW: 3>
 |  SOCK_RDM = <SocketKind.SOCK_RDM: 4>
 |  SOCK_SEQPACKET = <SocketKind.SOCK_SEQPACKET: 5>
 |  SOCK_STREAM = <SocketKind.SOCK_STREAM: 1>
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from enum.Enum:
 |
 |  name
 |      The name of the Enum member.
 |
 |  value
 |      The value of the Enum member.
 |
 |  ----------------------------------------------------------------------
 |  Readonly properties inherited from enum.EnumMeta:
 |
 |  __members__
 |      Returns a mapping of member name->value.
 |
 |      This mapping lists all enum members, including aliases. Note that this
 |      is a read-only view of the internal mapping.

🏷️ class socket (SocketType)

class socket(builtins.object)
 |  socket(family=AF_INET, type=SOCK_STREAM, proto=0) -> socket object
 |  socket(family=-1, type=-1, proto=-1, fileno=None) -> socket object
 |
 |  Open a socket of the given type.  The family argument specifies the
 |  address family; it defaults to AF_INET.  The type argument specifies
 |  whether this is a stream (SOCK_STREAM, this is the default)
 |  or datagram (SOCK_DGRAM) socket.  The protocol argument defaults to 0,
 |  specifying the default protocol.  Keyword arguments are accepted.
 |  The socket is created as non-inheritable.
 |
 |  When a fileno is passed in, family, type and proto are auto-detected,
 |  unless they are explicitly set.
 |
 |  A socket object represents one endpoint of a network connection.
 |
 |  Methods of socket objects (keyword arguments not allowed):
 |
 |  _accept() -- accept connection, returning new socket fd and client address
 |  bind(addr) -- bind the socket to a local address
 |  close() -- close the socket
 |  connect(addr) -- connect the socket to a remote address
 |  connect_ex(addr) -- connect, return an error code instead of an exception
 |  dup() -- return a new socket fd duplicated from fileno()
 |  fileno() -- return underlying file descriptor
 |  getpeername() -- return remote address [*]
 |  getsockname() -- return local address
 |  getsockopt(level, optname[, buflen]) -- get socket options
 |  gettimeout() -- return timeout or None
 |  listen([n]) -- start listening for incoming connections
 |  recv(buflen[, flags]) -- receive data
 |  recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer)
 |  recvfrom(buflen[, flags]) -- receive data and sender's address
 |  recvfrom_into(buffer[, nbytes, [, flags]) -- receive data and sender's address (into a buffer)
 |  sendall(data[, flags]) -- send all data
 |  send(data[, flags]) -- send data, may not send all of it
 |  sendto(data[, flags], addr) -- send data to a given address
 |  setblocking(bool) -- set or clear the blocking I/O flag
 |  getblocking() -- return True if socket is blocking, False if non-blocking
 |  setsockopt(level, optname, value[, optlen]) -- set socket options
 |  settimeout(None | float) -- set or clear the timeout
 |  shutdown(how) -- shut down traffic in one or both directions
 |
 |  [*] not available on all platforms!
 |
 |  Methods defined here:
 |
 |  __del__(...)
 |  __getattribute__(self, name, /) -- Return getattr(self, name).
 |  __init__(self, /, *args, **kwargs) -- Initialize self.
 |  __repr__(self, /) -- Return repr(self).
 |  bind(...) -- bind(address) -- Bind the socket to a local address.
 |  close(...) -- close() -- Close the socket.
 |  connect(...) -- connect(address) -- Connect the socket to a remote address.
 |  connect_ex(...) -- connect_ex(address) -> errno -- Returns error code instead of raising.
 |  detach(...) -- detach() -- Close socket object without closing fd.
 |  fileno(...) -- fileno() -> integer -- Return file descriptor.
 |  getblocking(...) -- Returns True if socket is in blocking mode.
 |  getpeername(...) -- Return address of remote endpoint.
 |  getsockname(...) -- Return address of local endpoint.
 |  getsockopt(...) -- Get a socket option.
 |  gettimeout(...) -- Returns timeout in seconds or None.
 |  listen(...) -- Enable server to accept connections.
 |  recv(...) -- Receive up to buffersize bytes.
 |  recv_into(...) -- Receive data into a buffer.
 |  recvfrom(...) -- Receive data and sender's address.
 |  recvfrom_into(...) -- Receive data into buffer and sender's address.
 |  recvmsg(...) -- Receive normal and ancillary data.
 |  recvmsg_into(...) -- Receive data into buffers and ancillary data.
 |  send(...) -- Send data string.
 |  sendall(...) -- Send all data repeatedly.
 |  sendmsg(...) -- Send normal and ancillary data.
 |  sendmsg_afalg(...) -- Set operation mode for AF_ALG.
 |  sendto(...) -- Send data to specified address.
 |  setblocking(...) -- Set blocking or non-blocking mode.
 |  setsockopt(...) -- Set socket option.
 |  settimeout(...) -- Set timeout on socket operations.
 |  shutdown(...) -- Shut down one or both directions.
 |
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  __new__(*args, **kwargs) -- Create and return a new object.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  family -- the socket family
 |  proto -- the socket protocol
 |  timeout -- the socket timeout
 |  type -- the socket type

⚠️ class error (OSError)

class OSError(Exception)
 |  Base class for I/O related errors.
 |  Method resolution order: OSError, Exception, BaseException, object
 |  Built-in subclasses: BlockingIOError, ChildProcessError, ConnectionError, ...
 |  Methods defined here: __init__, __reduce__, __str__
 |  Data descriptors: characters_written, errno, filename, filename2, strerror

⚠️ class gaierror

class gaierror(builtins.OSError)
 |  Method resolution order: gaierror, OSError, Exception, BaseException, object
 |  Data descriptors: __weakref__
 |  Inherits all methods from OSError.

⚠️ class herror

class herror(builtins.OSError)
 |  Method resolution order: herror, OSError, Exception, BaseException, object
 |  Data descriptors: __weakref__
 |  Inherits all methods from OSError.

⏰ class timeout (TimeoutError)

class TimeoutError(OSError)
 |  Timeout expired.
 |  Method resolution order: TimeoutError, OSError, Exception, BaseException, object
 |  Methods defined here: __init__
 |  Inherits all other methods from OSError.

⚙️ FUNCTIONS

📏 CMSG_LEN

CMSG_LEN(length) -> control message length

Return the total length, without trailing padding, of an ancillary data item with associated data of the given length. This value can often be used as the buffer size for recvmsg() to receive a single item of ancillary data, but RFC 3542 requires portable applications to use CMSG_SPACE() and thus include space for padding, even when the item will be the last in the buffer. Raises OverflowError if length is outside the permissible range of values.

📏 CMSG_SPACE

CMSG_SPACE(length) -> buffer size

Return the buffer size needed for recvmsg() to receive an ancillary data item with associated data of the given length, along with any trailing padding. The buffer space needed to receive multiple items is the sum of the CMSG_SPACE() values for their associated data lengths. Raises OverflowError if length is outside the permissible range of values.

🔒 close

close(integer) -> None

Close an integer socket file descriptor. This is like os.close(), but for sockets; on some platforms os.close() won't work for socket file descriptors.

🔗 create_connection

create_connection(address, timeout=<object object at 0x7f14ae2d0a20>, source_address=None)

Connect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple (host, port)) and return the socket object. Passing the optional *timeout* parameter will set the timeout on the socket instance before attempting to connect. If no *timeout* is supplied, the global default timeout setting returned by getdefaulttimeout() is used. If *source_address* is set it must be a tuple of (host, port) for the socket to bind as a source address before making the connection. A host of '' or port 0 tells the OS to use the default.

🖥️ create_server

create_server(address, *, family=<AddressFamily.AF_INET: 2>, backlog=None, reuse_port=False, dualstack_ipv6=False)

Convenience function which creates a SOCK_STREAM type socket bound to *address* (a 2-tuple (host, port)) and return the socket object.

>>> with create_server(('', 8000)) as server:
...     while True:
...         conn, addr = server.accept()
...         # handle new connection

🔁 dup

dup(integer) -> integer

Duplicate an integer socket file descriptor. This is like os.dup(), but for sockets; on some platforms os.dup() won't work for socket file descriptors.

📄 fromfd

fromfd(fd, family, type, proto=0) -> socket object

Create a socket object from a duplicate of the given file descriptor. The remaining arguments are the same as for socket().

🔍 getaddrinfo

getaddrinfo(host, port, family=0, type=0, proto=0, flags=0)

Resolve host and port into list of address info entries. Translate the host/port argument into a sequence of 5-tuples that contain all the necessary arguments for creating a socket connected to that service. host is a domain name, a string representation of an IPv4/v6 address or None. port is a string service name such as 'http', a numeric port number or None. By passing None as the value of host and port, you can pass NULL to the underlying C API. The family, type and proto arguments can be optionally specified in order to narrow the list of addresses returned. Passing zero as a value for each of these arguments selects the full range of results.

⏱️ getdefaulttimeout

getdefaulttimeout() -> timeout

Returns the default timeout in seconds (float) for new socket objects. A value of None indicates that new socket objects have no timeout. When the socket module is first imported, the default is None.

🏷️ getfqdn

getfqdn(name='')

Get fully qualified domain name from name. An empty argument is interpreted as meaning the local host. First the hostname returned by gethostbyaddr() is checked, then possibly existing aliases. In case no FQDN is available and name was given, it is returned unchanged. If name was empty, '0.0.0.0' or '::', hostname from gethostname() is returned.

🔍 gethostbyaddr

gethostbyaddr(host) -> (name, aliaslist, addresslist)

Return the true host name, a list of aliases, and a list of IP addresses, for a host. The host argument is a string giving a host name or IP number.

🔍 gethostbyname

gethostbyname(host) -> address

Return the IP address (a string of the form '255.255.255.255') for a host.

🔍 gethostbyname_ex

gethostbyname_ex(host) -> (name, aliaslist, addresslist)

Return the true host name, a list of aliases, and a list of IP addresses, for a host. The host argument is a string giving a host name or IP number.

🏠 gethostname

gethostname() -> string

Return the current host name.

🔍 getnameinfo

getnameinfo(sockaddr, flags) --> (host, port)

Get host and port for a sockaddr.

🔢 getprotobyname

getprotobyname(name) -> integer

Return the protocol number for the named protocol. (Rarely used.)

🔢 getservbyname

getservbyname(servicename[, protocolname]) -> integer

Return a port number from a service name and protocol name. The optional protocol name, if given, should be 'tcp' or 'udp', otherwise any protocol will match.

🔢 getservbyport

getservbyport(port[, protocolname]) -> string

Return the service name from a port number and protocol name. The optional protocol name, if given, should be 'tcp' or 'udp', otherwise any protocol will match.

🌐 has_dualstack_ipv6

has_dualstack_ipv6()

Return True if the platform supports creating a SOCK_STREAM socket which can handle both AF_INET and AF_INET6 (IPv4 / IPv6) connections.

🔢 htonl

htonl(integer) -> integer

Convert a 32-bit integer from host to network byte order.

🔢 htons

htons(integer) -> integer

Convert a 16-bit unsigned integer from host to network byte order.

🌐 if_indextoname

if_indextoname(if_index)

Returns the interface name corresponding to the interface index if_index.

🌐 if_nameindex

if_nameindex()

Returns a list of network interface information (index, name) tuples.

🌐 if_nametoindex

if_nametoindex(if_name)

Returns the interface index corresponding to the interface name if_name.

🔢 inet_aton

inet_aton(string) -> bytes giving packed 32-bit IP representation

Convert an IP address in string format (123.45.67.89) to the 32-bit packed binary format used in low-level network functions.

🔢 inet_ntoa

inet_ntoa(packed_ip) -> ip_address_string

Convert an IP address from 32-bit packed binary format to string format.

🔢 inet_ntop

inet_ntop(af, packed_ip) -> string formatted IP address

Convert a packed IP address of the given family to string format.

🔢 inet_pton

inet_pton(af, ip) -> packed IP address string

Convert an IP address from string format to a packed string suitable for use with low-level network functions.

🔢 ntohl

ntohl(integer) -> integer

Convert a 32-bit integer from network to host byte order.

🔢 ntohs

ntohs(integer) -> integer

Convert a 16-bit unsigned integer from network to host byte order.

📥 recv_fds

recv_fds(sock, bufsize, maxfds, flags=0) -> (data, list of file descriptors, msg_flags, address)

Receive up to maxfds file descriptors returning the message data and a list containing the descriptors.

📤 send_fds

send_fds(sock, buffers, fds, flags=0, address=None) -> integer

Send the list of file descriptors fds over an AF_UNIX socket.

⏱️ setdefaulttimeout

setdefaulttimeout(timeout)

Set the default timeout in seconds (float) for new socket objects. A value of None indicates that new socket objects have no timeout. When the socket module is first imported, the default is None.

🏠 sethostname

sethostname(name)

Sets the hostname to name.

🔗 socketpair

socketpair(family=None, type=<SocketKind.SOCK_STREAM: 1>, proto=0) -> (socket object, socket object)

Create a pair of socket objects from the sockets returned by the platform socketpair() function. The arguments are the same as for socket() except the default family is AF_UNIX if defined on the platform; otherwise, the default is AF_INET.

📊 DATA

(Extensive list of constants; see the full module documentation for details.)

Key constants include:

Full list is available in the module source.

📁 FILE

/usr/lib/python3.10/socket.py
socket
📛 NAME 🚀 Quick Reference 📚 MODULE REFERENCE 📝 DESCRIPTION
🔧 Functions 🎯 Special objects 🔢 IntEnum constants 🔢 Integer constants
🏛️ CLASSES
🏷️ class AddressFamily 🏷️ class SocketKind 🏷️ class socket (SocketType) ⚠️ class error (OSError) ⚠️ class gaierror ⚠️ class herror ⏰ class timeout (TimeoutError)
⚙️ FUNCTIONS
📏 CMSG_LEN 📏 CMSG_SPACE 🔒 close 🔗 create_connection 🖥️ create_server 🔁 dup 📄 fromfd 🔍 getaddrinfo ⏱️ getdefaulttimeout 🏷️ getfqdn 🔍 gethostbyaddr 🔍 gethostbyname 🔍 gethostbyname_ex 🏠 gethostname 🔍 getnameinfo 🔢 getprotobyname 🔢 getservbyname 🔢 getservbyport 🌐 has_dualstack_ipv6 🔢 htonl 🔢 htons 🌐 if_indextoname 🌐 if_nameindex 🌐 if_nametoindex 🔢 inet_aton 🔢 inet_ntoa 🔢 inet_ntop 🔢 inet_pton 🔢 ntohl 🔢 ntohs 📥 recv_fds 📤 send_fds ⏱️ setdefaulttimeout 🏠 sethostname 🔗 socketpair
📊 DATA 📁 FILE

Generated by phpman v4.10.0-7-g98e9fd5 · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-09-02 20:08 @216.73.216.239
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
Valid XHTML 1.0 Transitional!Valid CSS!

^_top_^