socket — 低階網路介面

原始碼:Lib/socket.py


這個模組提供了操作 BSD socket 的介面。這在所有現代 Unix 系統、Windows、MacOS,以及一些其他平台上都可用。

備註

由於是呼叫作業系統的 socket API,某些行為可能會因平台而有所差異。

可用性: not WASI.

此模組在 WebAssembly 平台上不起作用或無法使用。更多資訊請參閱 WebAssembly 平台

Python 的介面是將 Unix 的系統呼叫和 socket 函式庫介面直接轉換成 Python 的物件導向風格:socket() 函式會回傳一個 socket 物件,這個物件的方法實作了各種 socket 系統呼叫。與 C 語言介面相比,參數型別較為高階:就像 Python 文件操作中的 read()write() 一樣,接收操作時會自動分配緩衝區,而發送操作時的緩衝區長度則是隱含的。

也參考

socketserver 模組

簡化編寫網路伺服器的類別。

ssl 模組

對 socket 物件的 TLS/SSL 的包裝器 (wrapper)。

Socket 系列家族

Depending on the system and the build options, various socket families are supported by this module.

The address format required by a particular socket object is automatically selected based on the address family specified when the socket object was created. Socket addresses are represented as follows:

  • The address of an AF_UNIX socket bound to a file system node is represented as a string, using the file system encoding and the 'surrogateescape' error handler (see PEP 383). An address in Linux's abstract namespace is returned as a bytes-like object with an initial null byte; note that sockets in this namespace can communicate with normal file system sockets, so programs intended to run on Linux may need to deal with both types of address. A string or bytes-like object can be used for either type of address when passing it as an argument.

    在 3.3 版的變更: Previously, AF_UNIX socket paths were assumed to use UTF-8 encoding.

    在 3.5 版的變更: Writable bytes-like object is now accepted.

  • A pair (host, port) is used for the AF_INET address family, where host is a string representing either a hostname in internet domain notation like 'daring.cwi.nl' or an IPv4 address like '100.50.200.5', and port is an integer.

    • For IPv4 addresses, two special forms are accepted instead of a host address: '' represents INADDR_ANY, which is used to bind to all interfaces, and the string '<broadcast>' represents INADDR_BROADCAST. This behavior is not compatible with IPv6, therefore, you may want to avoid these if you intend to support IPv6 with your Python programs.

  • For AF_INET6 address family, a four-tuple (host, port, flowinfo, scope_id) is used, where flowinfo and scope_id represent the sin6_flowinfo and sin6_scope_id members in struct sockaddr_in6 in C. For socket module methods, flowinfo and scope_id can be omitted just for backward compatibility. Note, however, omission of scope_id can cause problems in manipulating scoped IPv6 addresses.

    在 3.7 版的變更: For multicast addresses (with scope_id meaningful) address may not contain %scope_id (or zone id) part. This information is superfluous and may be safely omitted (recommended).

  • AF_NETLINK socket 會以成對的 (pid, groups) 來表示。

  • Linux-only support for TIPC is available using the AF_TIPC address family. TIPC is an open, non-IP based networked protocol designed for use in clustered computer environments. Addresses are represented by a tuple, and the fields depend on the address type. The general tuple form is (addr_type, v1, v2, v3 [, scope]), where:

    • addr_type is one of TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, or TIPC_ADDR_ID.

    • scope is one of TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and TIPC_NODE_SCOPE.

    • If addr_type is TIPC_ADDR_NAME, then v1 is the server type, v2 is the port identifier, and v3 should be 0.

      If addr_type is TIPC_ADDR_NAMESEQ, then v1 is the server type, v2 is the lower port number, and v3 is the upper port number.

      If addr_type is TIPC_ADDR_ID, then v1 is the node, v2 is the reference, and v3 should be set to 0.

  • A tuple (interface, ) is used for the AF_CAN address family, where interface is a string representing a network interface name like 'can0'. The network interface name '' can be used to receive packets from all network interfaces of this family.

    • CAN_ISOTP protocol requires a tuple (interface, rx_addr, tx_addr) where both additional parameters are unsigned long integer that represent a CAN identifier (standard or extended).

    • CAN_J1939 protocol requires a tuple (interface, name, pgn, addr) where additional parameters are 64-bit unsigned integer representing the ECU name, a 32-bit unsigned integer representing the Parameter Group Number (PGN), and an 8-bit integer representing the address.

  • A string or a tuple (id, unit) is used for the SYSPROTO_CONTROL protocol of the PF_SYSTEM family. The string is the name of a kernel control using a dynamically assigned ID. The tuple can be used if ID and unit number of the kernel control are known or if a registered ID is used.

    在 3.3 版被加入.

  • AF_BLUETOOTH supports the following protocols and address formats:

    • BTPROTO_L2CAP accepts a tuple (bdaddr, psm[, cid[, bdaddr_type]]) where:

      • bdaddr 是一個指定藍牙位址的字串。

      • psm is an integer specifying the Protocol/Service Multiplexer.

      • cid is an optional integer specifying the Channel Identifier. If not given, defaults to zero.

      • bdaddr_type is an optional integer specifying the address type; one of BDADDR_BREDR (default), BDADDR_LE_PUBLIC, BDADDR_LE_RANDOM.

      在 3.14 版的變更: 新增 cidbdaddr_type 欄位。

    • BTPROTO_RFCOMM accepts (bdaddr, channel) where bdaddr is the Bluetooth address as a string and channel is an integer.

    • BTPROTO_HCI accepts a format that depends on your OS.

      • On Linux it accepts an integer device_id or a tuple (device_id, [channel]) where device_id specifies the number of the Bluetooth device, and channel is an optional integer specifying the HCI channel (HCI_CHANNEL_RAW by default).

      • On FreeBSD, NetBSD and DragonFly BSD it accepts bdaddr where bdaddr is the Bluetooth address as a string.

      在 3.2 版的變更: 加入對 NetBSD 和 DragonFlyBSD 的支援。

      在 3.13.3 版的變更: 新增對 FreeBSD 的支援。

      在 3.14 版的變更: Added channel field. device_id not packed in a tuple is now accepted.

    • BTPROTO_SCO accepts bdaddr where bdaddr is the Bluetooth address as a string or a bytes object. (ex. '12:23:34:45:56:67' or b'12:23:34:45:56:67')

      在 3.14 版的變更: 新增對 FreeBSD 的支援。

  • AF_ALG is a Linux-only socket based interface to Kernel cryptography. An algorithm socket is configured with a tuple of two to four elements (type, name [, feat [, mask]]), where:

    • type is the algorithm type as string, e.g. aead, hash, skcipher or rng.

    • name is the algorithm name and operation mode as string, e.g. sha256, hmac(sha256), cbc(aes) or drbg_nopr_ctr_aes256.

    • feat and mask are unsigned 32bit integers.

    可用性: Linux >= 2.6.38.

    Some algorithm types require more recent Kernels.

    在 3.6 版被加入.

  • AF_VSOCK allows communication between virtual machines and their hosts. The sockets are represented as a (CID, port) tuple where the context ID or CID and port are integers.

    可用性: Linux >= 3.9

    請見 vsock(7)

    在 3.7 版被加入.

  • AF_PACKET is a low-level interface directly to network devices. The addresses are represented by the tuple (ifname, proto[, pkttype[, hatype[, addr]]]) where:

    • ifname - String specifying the device name.

    • proto - The Ethernet protocol number. May be ETH_P_ALL to capture all protocols, one of the ETHERTYPE_* constants or any other Ethernet protocol number.

    • pkttype - Optional integer specifying the packet type:

      • PACKET_HOST (the default) - Packet addressed to the local host.

      • PACKET_BROADCAST - Physical-layer broadcast packet.

      • PACKET_MULTICAST - Packet sent to a physical-layer multicast address.

      • PACKET_OTHERHOST - Packet to some other host that has been caught by a device driver in promiscuous mode.

      • PACKET_OUTGOING - Packet originating from the local host that is looped back to a packet socket.

    • hatype - Optional integer specifying the ARP hardware address type.

    • addr - Optional bytes-like object specifying the hardware physical address, whose interpretation depends on the device.

    可用性: Linux >= 2.2.

  • AF_QIPCRTR is a Linux-only socket based interface for communicating with services running on co-processors in Qualcomm platforms. The address family is represented as a (node, port) tuple where the node and port are non-negative integers.

    可用性: Linux >= 4.7.

    在 3.8 版被加入.

  • IPPROTO_UDPLITE is a variant of UDP which allows you to specify what portion of a packet is covered with the checksum. It adds two socket options that you can change. self.setsockopt(IPPROTO_UDPLITE, UDPLITE_SEND_CSCOV, length) will change what portion of outgoing packets are covered by the checksum and self.setsockopt(IPPROTO_UDPLITE, UDPLITE_RECV_CSCOV, length) will filter out packets which cover too little of their data. In both cases length should be in range(8, 2**16, 8).

    Such a socket should be constructed with socket(AF_INET, SOCK_DGRAM, IPPROTO_UDPLITE) for IPv4 or socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDPLITE) for IPv6.

    可用性: Linux >= 2.6.20, FreeBSD >= 10.1

    在 3.9 版被加入.

  • AF_HYPERV is a Windows-only socket based interface for communicating with Hyper-V hosts and guests. The address family is represented as a (vm_id, service_id) tuple where the vm_id and service_id are UUID strings.

    The vm_id is the virtual machine identifier or a set of known VMID values if the target is not a specific virtual machine. Known VMID constants defined on socket are:

    • HV_GUID_ZERO

    • HV_GUID_BROADCAST

    • HV_GUID_WILDCARD - Used to bind on itself and accept connections from all partitions.

    • HV_GUID_CHILDREN - Used to bind on itself and accept connection from child partitions.

    • HV_GUID_LOOPBACK - Used as a target to itself.

    • HV_GUID_PARENT - When used as a bind accepts connection from the parent partition. When used as an address target it will connect to the parent partition.

    The service_id is the service identifier of the registered service.

    在 3.12 版被加入.

If you use a hostname in the host portion of IPv4/v6 socket address, the program may show a nondeterministic behavior, as Python uses the first address returned from the DNS resolution. The socket address will be resolved differently into an actual IPv4/v6 address, depending on the results from DNS resolution and/or the host configuration. For deterministic behavior use a numeric address in host portion.

All errors raise exceptions. The normal exceptions for invalid argument types and out-of-memory conditions can be raised. Errors related to socket or address semantics raise OSError or one of its subclasses.

Non-blocking mode is supported through setblocking(). A generalization of this based on timeouts is supported through settimeout().

模組內容

The module socket exports the following elements.

例外

exception socket.error

一個已棄用的 OSError 的別名。

在 3.3 版的變更: Following PEP 3151, this class was made an alias of OSError.

exception socket.herror

A subclass of OSError, this exception is raised for address-related errors, i.e. for functions that use h_errno in the POSIX C API, including gethostbyname_ex() and gethostbyaddr(). The accompanying value is a pair (h_errno, string) representing an error returned by a library call. h_errno is a numeric value, while string represents the description of h_errno, as returned by the hstrerror() C function.

在 3.3 版的變更: This class was made a subclass of OSError.

exception socket.gaierror

A subclass of OSError, this exception is raised for address-related errors by getaddrinfo() and getnameinfo(). The accompanying value is a pair (error, string) representing an error returned by a library call. string represents the description of error, as returned by the gai_strerror() C function. The numeric error value will match one of the EAI_* constants defined in this module.

在 3.3 版的變更: This class was made a subclass of OSError.

exception socket.timeout

A deprecated alias of TimeoutError.

A subclass of OSError, this exception is raised when a timeout occurs on a socket which has had timeouts enabled via a prior call to settimeout() (or implicitly through setdefaulttimeout()). The accompanying value is a string whose value is currently always "timed out".

在 3.3 版的變更: This class was made a subclass of OSError.

在 3.10 版的變更: This class was made an alias of TimeoutError.

常數

The AF_* and SOCK_* constants are now AddressFamily and SocketKind IntEnum collections.

在 3.4 版被加入.

socket.AF_UNIX
socket.AF_INET
socket.AF_INET6

These constants represent the address (and protocol) families, used for the first argument to socket(). If the AF_UNIX constant is not defined then this protocol is unsupported. More constants may be available depending on the system.

socket.AF_UNSPEC

AF_UNSPEC means that getaddrinfo() should return socket addresses for any address family (either IPv4, IPv6, or any other) that can be used.

socket.SOCK_STREAM
socket.SOCK_DGRAM
socket.SOCK_RAW
socket.SOCK_RDM
socket.SOCK_SEQPACKET

These constants represent the socket types, used for the second argument to socket(). More constants may be available depending on the system. (Only SOCK_STREAM and SOCK_DGRAM appear to be generally useful.)

socket.SOCK_CLOEXEC
socket.SOCK_NONBLOCK

These two constants, if defined, can be combined with the socket types and allow you to set some flags atomically (thus avoiding possible race conditions and the need for separate calls).

也參考

Secure File Descriptor Handling for a more thorough explanation.

可用性: Linux >= 2.6.27.

在 3.2 版被加入.

SO_*
socket.SOMAXCONN
MSG_*
SOL_*
SCM_*
IPPROTO_*
IPPORT_*
INADDR_*
IP_*
IPV6_*
EAI_*
AI_*
NI_*
TCP_*

Many constants of these forms, documented in the Unix documentation on sockets and/or the IP protocol, are also defined in the socket module. They are generally used in arguments to the setsockopt() and getsockopt() methods of socket objects. In most cases, only those symbols that are defined in the Unix header files are defined; for a few symbols, default values are provided.

在 3.6 版的變更: SO_DOMAIN, SO_PROTOCOL, SO_PEERSEC, SO_PASSSEC, TCP_USER_TIMEOUT, TCP_CONGESTION were added.

在 3.6.5 版的變更: Added support for TCP_FASTOPEN, TCP_KEEPCNT on Windows platforms when available.

在 3.7 版的變更: 新增 TCP_NOTSENT_LOWAT

Added support for TCP_KEEPIDLE, TCP_KEEPINTVL on Windows platforms when available.

在 3.10 版的變更: IP_RECVTOS was added. Added TCP_KEEPALIVE. On MacOS this constant can be used in the same way that TCP_KEEPIDLE is used on Linux.

在 3.11 版的變更: Added TCP_CONNECTION_INFO. On MacOS this constant can be used in the same way that TCP_INFO is used on Linux and BSD.

在 3.12 版的變更: Added SO_RTABLE and SO_USER_COOKIE. On OpenBSD and FreeBSD respectively those constants can be used in the same way that SO_MARK is used on Linux. Also added missing TCP socket options from Linux: TCP_MD5SIG, TCP_THIN_LINEAR_TIMEOUTS, TCP_THIN_DUPACK, TCP_REPAIR, TCP_REPAIR_QUEUE, TCP_QUEUE_SEQ, TCP_REPAIR_OPTIONS, TCP_TIMESTAMP, TCP_CC_INFO, TCP_SAVE_SYN, TCP_SAVED_SYN, TCP_REPAIR_WINDOW, TCP_FASTOPEN_CONNECT, TCP_ULP, TCP_MD5SIG_EXT, TCP_FASTOPEN_KEY, TCP_FASTOPEN_NO_COOKIE, TCP_ZEROCOPY_RECEIVE, TCP_INQ, TCP_TX_DELAY. Added IP_PKTINFO, IP_UNBLOCK_SOURCE, IP_BLOCK_SOURCE, IP_ADD_SOURCE_MEMBERSHIP, IP_DROP_SOURCE_MEMBERSHIP.

在 3.13 版的變更: Added SO_BINDTOIFINDEX. On Linux this constant can be used in the same way that SO_BINDTODEVICE is used, but with the index of a network interface instead of its name.

在 3.14 版的變更: Added missing IP_FREEBIND, IP_RECVERR, IPV6_RECVERR, IP_RECVTTL, and IP_RECVORIGDSTADDR on Linux.

在 3.14 版的變更: Added support for TCP_QUICKACK on Windows platforms when available.

socket.AF_CAN
socket.PF_CAN
SOL_CAN_*
CAN_*

Many constants of these forms, documented in the Linux documentation, are also defined in the socket module.

可用性: Linux >= 2.6.25, NetBSD >= 8.

在 3.3 版被加入.

在 3.11 版的變更: 新增對 NetBSD 的支援。

在 3.14 版的變更: Restored missing CAN_RAW_ERR_FILTER on Linux.

socket.CAN_BCM
CAN_BCM_*

CAN_BCM, in the CAN protocol family, is the broadcast manager (BCM) protocol. Broadcast manager constants, documented in the Linux documentation, are also defined in the socket module.

可用性: Linux >= 2.6.25.

備註

The CAN_BCM_CAN_FD_FRAME flag is only available on Linux >= 4.8.

在 3.4 版被加入.

socket.CAN_RAW_FD_FRAMES

Enables CAN FD support in a CAN_RAW socket. This is disabled by default. This allows your application to send both CAN and CAN FD frames; however, you must accept both CAN and CAN FD frames when reading from the socket.

This constant is documented in the Linux documentation.

可用性: Linux >= 3.6.

在 3.5 版被加入.

socket.CAN_RAW_JOIN_FILTERS

Joins the applied CAN filters such that only CAN frames that match all given CAN filters are passed to user space.

This constant is documented in the Linux documentation.

可用性: Linux >= 4.1.

在 3.9 版被加入.

socket.CAN_ISOTP

CAN_ISOTP, in the CAN protocol family, is the ISO-TP (ISO 15765-2) protocol. ISO-TP constants, documented in the Linux documentation.

可用性: Linux >= 2.6.25.

在 3.7 版被加入.

socket.CAN_J1939

CAN_J1939, in the CAN protocol family, is the SAE J1939 protocol. J1939 constants, documented in the Linux documentation.

可用性: Linux >= 5.4.