socket — 低级网络接口

源代码: Lib/socket.py


此模块提供访问 BSD socket 接口。它可用于所有现代 Unix 系统、Windows、MacOS 及可能的其它平台。

注意

某些行为可能从属平台,由于调用的是操作系统的套接字 API。

Python 接口是 Unix 系统调用和套接字库接口到 Python 面向对象风格的简明直译: socket() 函数返回 套接字对象 其方法有实现各种套接字系统调用。参数类型比 C 接口中的要高级一些:如同采用 read() and write() 操作 Python 文件,接收操作的缓冲分配是自动的,而发送操作的缓冲长度是隐式的。

另请参阅

模块 socketserver

简化编写网络服务器的类。

模块 ssl

套接字对象的 TLS/SSL 包裹器。

套接字系列

由此模块支持的各种套接字系列,从属系统和构建选项。

特定套接字对象要求的地址格式是基于指定地址族自动选择的,当创建套接字对象时。套接字地址表示如下:

  • 地址对于 AF_UNIX (绑定到文件系统节点的) 套接字将表示成字符串,使用文件系统编码和 'surrogateescape' 错误处理程序 (见 PEP 383 )。Linux 抽象名称空间中的地址将返回成 像字节对象 采用初始 null 字节;注意,在此名称空间中的套接字可以与正常文件系统套接字通信,因此打算在 Linux 上运行的程序可能需要处理 2 种地址类型。字符串或像字节对象可用作任一地址类型,当将它作为自变量传递时。

    3.3 版改变: 先前, AF_UNIX 套接字路径是假定使用 UTF-8 编码。

    3.5 版改变: 可写 像字节对象 现在被接受。

  • 一对 (host, port) 用于 AF_INET 地址族,其中 host 是 Internet 域表示法的主机名表示字符串,像 'daring.cwi.nl' 或 IPv4 地址像 '100.50.200.5' ,和 port 是整数。

    • 对于 IPv4 地址,接受 2 种特殊形式而不是主机地址: '' 表示 INADDR_ANY 用于绑定到所有接口,而字符串 '<broadcast>' 表示 INADDR_BROADCAST 。此行为不兼容 IPv6,因此,可能想要避免这些,若打算采用 Python 程序支持 IPv6。

  • For AF_INET6 地址族 4 元组 (host, port, flowinfo, scope_id) 被使用,其中 flowinfo and scope_id 表示 sin6_flowinfo and sin6_scope_id 成员在 struct sockaddr_in6 在 C 中。对于 socket 模块方法, flowinfo and scope_id 可以省略只为向后兼容。注意,不管怎样,省略 scope_id 可能导致问题,当操纵 IPv6 作用域地址时。

    3.7 版改变: 对于多点播送地址 (采用 scope_id 有意义) address 可能不包含 %scope_id (或 zone id ) 部分。此信息是多余的,且可以安全省略 (推荐)。

  • AF_NETLINK 套接字表示为成对 (pid, groups) .

  • 可获得仅 Linux 对 TIPC 的支持使用 AF_TIPC 地址族。TIPC 是开放的、基于非 IP 的网络协议,设计用于集群计算机环境。地址由元组表示,且字段从属地址类型。一般元组形式为 (addr_type, v1, v2, v3 [, scope]) ,其中:

    • addr_type 是某一 TIPC_ADDR_NAMESEQ , TIPC_ADDR_NAME ,或 TIPC_ADDR_ID .

    • scope 是某一 TIPC_ZONE_SCOPE , TIPC_CLUSTER_SCOPE ,和 TIPC_NODE_SCOPE .

    • addr_type is TIPC_ADDR_NAME ,那么 v1 是服务器类型, v2 是端口标识符,和 v3 应该为 0。

      addr_type is TIPC_ADDR_NAMESEQ ,那么 v1 是服务器类型, v2 是更低端口号,和 v3 是更高端口号。

      addr_type is TIPC_ADDR_ID ,那么 v1 是节点, v2 是引用,和 v3 应被设为 0。

  • 元组 (interface, ) 用于 AF_CAN 地址族,其中 interface 是网络接口名称表示字符串,像 'can0' 。网络接口名称 '' 可以用于从此系列的所有网络接口接收数据包。

    • CAN_ISOTP 协议要求元组 (interface, rx_addr, tx_addr) 其中 2 额外参数是表示 CAN 标识符 (标准或扩展) 的无符号长整数。

    • CAN_J1939 协议要求元组 (interface, name, pgn, addr) 其中额外参数是表示 ECU 名称的 64 位无符号整数、表示 PGN (参数组编号) 的 32 位无符号整数和表示地址的 8 位整数。

  • 字符串或元组 (id, unit) 用于 SYSPROTO_CONTROL 协议的 PF_SYSTEM 系列。字符串是使用动态赋值 ID 的内核控件名称。可以使用元组,若 ID 和内核控件的单元号已知 (或者,若使用注册 ID)。

    3.3 版新增。

  • AF_BLUETOOTH 支持下列协议和地址格式:

    • BTPROTO_L2CAP 接受 (bdaddr, psm) where bdaddr 是作为字符串的蓝牙地址和 psm 是整数。

    • BTPROTO_RFCOMM 接受 (bdaddr, channel) where bdaddr 是作为字符串的蓝牙地址和 channel 是整数。

    • BTPROTO_HCI 接受 (device_id,) where device_id 是带蓝牙接口地址的整数或字符串 (这从属 OS;NetBSD 和 DragonFlyBSD 期望蓝牙地址,而其它的期望整数)。

      3.2 版改变: 添加支持 NetBSD 和 DragonFlyBSD。

    • BTPROTO_SCO 接受 bdaddr where bdaddr bytes 对象包含字符串格式的蓝牙地址。(如 b'12:23:34:45:56:67' ) FreeBSD 不支持此协议。

  • AF_ALG 是基于仅 Linux 套接字的内核加密接口。算法套接字的配置采用的元组有 2 个到 4 个元素 (type, name [, feat [, mask]]) ,其中:

    • type 是字符串形式的算法类型,如 aead , hash , skcipher or rng .

    • name 是字符串形式的算法名称和操作模式,如 sha256 , hmac(sha256) , cbc(aes) or drbg_nopr_ctr_aes256 .

    • feat and mask 是无符号 32 位整数。

    可用性 :Linux 2.6.38,某些算法类型要求更新内核。

    3.6 版新增。

  • AF_VSOCK 允许在虚拟机及其主机之间通信。套接字的表示按 (CID, port) 元组,其中上下文 ID (或 CID) 和端口是整数。

    可用性 : Linux >= 4.8 QEMU >= 2.8 ESX >= 4.0 ESX Workstation >= 6.5.

    3.7 版新增。

  • AF_PACKET 是直接到网络设备的低级接口。数据包的表示通过元组 (ifname, proto[, pkttype[, hatype[, addr]]]) 其中:

    • ifname - 指定设备名称的字符串。

    • proto - 指定以太网协议编号的网络字节次序整数。

    • pkttype - 指定数据包类型的可选整数:

      • PACKET_HOST (默认) - 发往本地主机的数据包。

      • PACKET_BROADCAST - 物理层广播数据包。

      • PACKET_MULTIHOST - 发送给物理层多点播送地址的数据包。

      • PACKET_OTHERHOST - 到某些其它主机的数据包 (已被混杂模式设备驱动程序捕获)。

      • PACKET_OUTGOING - 来源自本地主机的数据包 (循环回数据包套接字)。

    • hatype - 指定 ARP 硬件地址类型的可选整数。

    • addr - 指定硬件物理地址的可选像字节对象 (其解释从属设备)。

  • AF_QIPCRTR 是基于仅 Linux 的套接字接口 (用于与 Qualcomm 平台协处理器中运行的服务进行通信)。地址族的表示按 (node, port) 元组其中 node and port 是非负整数。

    3.8 版新增。

  • IPPROTO_UDPLITE 是允许指定校验和覆盖数据包部分的 UDP 变体。它有添加 2 个可以改变的套接字选项。 self.setsockopt(IPPROTO_UDPLITE, UDPLITE_SEND_CSCOV, length) 将改变由校验和覆盖的传出数据包部分而 self.setsockopt(IPPROTO_UDPLITE, UDPLITE_RECV_CSCOV, length) 将过滤掉覆盖太少数据的数据包。在这 2 种情况下 length 应该在 range(8, 2**16, 8) .

    这种套接字的构造应该采用 socket(AF_INET, SOCK_DGRAM, IPPROTO_UDPLITE) 对于 IPv4 或 socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDPLITE) 对于 IPv6。

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

    3.9 版新增。

若使用主机名在 host 部分为 IPv4/v6 套接字地址,程序可能展示不确定行为,因为 Python 使用解析自 DNS 的第一返回地址。套接字地址将以不同方式被解析成实际 IPv4/v6 地址,取决于解析自 DNS 的结果和/或主机配置。对于确定性行为,使用数值地址在 host 部分。

所有错误引发异常。可以引发正常异常,对于无效自变量类型和内存不足情况;从 Python 3.3 开始,与套接字或地址语义相关的错误会引发 OSError 或其子类之一 (它们用于引发 socket.error ).

支持非阻塞模式透过 setblocking() 。支持基于超时的一般化透过 settimeout() .

模块内容

模块 socket 导出下列元素。

异常

exception socket. error

弃用别名化的 OSError .

3.3 版改变: Following PEP 3151 ,此类是别名化的 OSError .

exception socket. herror

子类化的 OSError ,此异常被引发对于地址相关错误,即,对于函数有使用 h_errno 在 POSIX C API,包括 gethostbyname_ex() and gethostbyaddr() 。伴随值是一对 (h_errno, string) 表示由库调用返回的错误。 h_errno 是数值,而 string 表示描述对于 h_errno ,作为返回通过 hstrerror() C 函数。

3.3 版改变: 此类是子类化的 OSError .

exception socket. gaierror

子类化的 OSError ,此异常被引发对于地址相关错误通过 getaddrinfo() and getnameinfo() 。伴随值是一对 (error, string) 表示由库调用返回的错误。 string 表示描述对于 error ,作为返回通过 gai_strerror() C 函数。数值 error 值将匹配某一 EAI_* 常量 (在此模块中有定义)。

3.3 版改变: 此类是子类化的 OSError .

exception socket. timeout

子类化的 OSError ,此异常被引发当已启用超时的套接字发生超时凭借先前调用 settimeout() (或隐式透过 setdefaulttimeout() )。伴随值是目前始终为 timed out 的字符串。

3.3 版改变: 此类是子类化的 OSError .

常量

AF_* 和 SOCK_* 常量现在是 AddressFamily and SocketKind IntEnum 集合。

3.4 版新增。

socket. AF_UNIX
socket. AF_INET
socket. AF_INET6

这些常量表示地址 (和协议) 系列,用作第一自变量对于 socket() 。若 AF_UNIX 常量未定义,那么此协议不被支持。更多可用常量从属系统。

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

这些常量表示套接字类型,用作第 2 自变量对于 socket() 。更多可用常量从属系统。(仅 SOCK_STREAM and SOCK_DGRAM 似乎很有用,一般来说。)

socket. SOCK_CLOEXEC
socket. SOCK_NONBLOCK

若有定义这 2 常量,可以组合套接字类型并允许以原子方式设置一些标志 (从而避免可能的竞争条件和需要单独调用)。

另请参阅

安全文件描述符处理 了解更彻底解释。

可用性 : 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 被添加。

3.6.5 版改变: 在 Windows, TCP_FASTOPEN , TCP_KEEPCNT 会出现若运行时 Windows 支持。

3.7 版改变: TCP_NOTSENT_LOWAT 被添加。

在 Windows, TCP_KEEPIDLE , TCP_KEEPINTVL 会出现若运行时 Windows 支持。

socket. AF_CAN
socket. PF_CAN
SOL_CAN_*
CAN_*

Linux 文档编制有文档化这些形式的许多常量,在 socket 模块也有定义。

可用性 : Linux >= 2.6.25.

3.3 版新增。

socket. CAN_BCM
CAN_BCM_*

CAN_BCM 属于 CAN 协议族,是 BCM (广播管理器) 协议。Linux 文档编制有文档化广播管理器常量,在 socket 模块也有定义。

可用性 : Linux >= 2.6.25.

注意

CAN_BCM_CAN_FD_FRAME 标志只可用于 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.

此常量的文档化在 Linux 文档编制。

可用性 : 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.

此常量的文档化在 Linux 文档编制。

可用性 : 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.

3.9 版新增。

socket. AF_PACKET
socket. PF_PACKET
PACKET_*

Linux 文档编制有文档化这些形式的许多常量,在 socket 模块也有定义。

可用性 : Linux >= 2.2.

socket. AF_RDS
socket. PF_RDS
socket. SOL_RDS
RDS_*

Linux 文档编制有文档化这些形式的许多常量,在 socket 模块也有定义。

可用性 : Linux >= 2.6.30.

3.3 版新增。

socket. SIO_RCVALL
socket. SIO_KEEPALIVE_VALS
socket. SIO_LOOPBACK_FAST_PATH
RCVALL_*

Constants for Windows’ WSAIoctl(). The constants are used as arguments to the ioctl() method of socket objects.

3.6 版改变: SIO_LOOPBACK_FAST_PATH 被添加。

TIPC_*

TIPC related constants, matching the ones exported by the C socket API. See the TIPC documentation for more information.

socket. AF_ALG
socket. SOL_ALG
ALG_*

Linux 内核加密常量。

可用性 : Linux >= 2.6.38.

3.6 版新增。

socket. AF_VSOCK
socket. IOCTL_VM_SOCKETS_GET_LOCAL_CID
VMADDR*
SO_VM*

Linux 主机/访客通信常量。

可用性 : Linux >= 4.8.

3.7 版新增。

可用性 : BSD, OSX.

3.4 版新增。

socket. has_ipv6

This constant contains a boolean value which indicates if IPv6 is supported on this platform.

socket. BDADDR_ANY
socket. BDADDR_LOCAL

These are string constants containing Bluetooth addresses with special meanings. For example, BDADDR_ANY can be used to indicate any address when specifying the binding socket with BTPROTO_RFCOMM .

socket. HCI_FILTER
socket. HCI_TIME_STAMP
socket. HCI_DATA_DIR

For use with BTPROTO_HCI . HCI_FILTER is not available for NetBSD or DragonFlyBSD. HCI_TIME_STAMP and HCI_DATA_DIR are not available for FreeBSD, NetBSD, or DragonFlyBSD.

socket. AF_QIPCRTR

Constant for Qualcomm’s IPC router protocol, used to communicate with service providing remote processors.

可用性 : Linux >= 4.7.

函数

创建套接字

以下函数都创建 套接字对象 .

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

使用给定地址族、套接字类型和协议编号,创建新的套接字。地址族应该是 AF_INET (默认), AF_INET6 , AF_UNIX , AF_CAN , AF_PACKET ,或 AF_RDS 。套接字类型应该是 SOCK_STREAM (默认), SOCK_DGRAM , SOCK_RAW 或者或许某一其它 SOCK_ 常量。协议编号通常为 0 且可以省略,或者若地址族为 AF_CAN 协议应为某一 CAN_RAW , CAN_BCM , CAN_ISOTP or CAN_J1939 .

fileno 有指定,值对于 系列 , type ,和 proto 是自动检测从指定文件描述符。可以否决自动检测通过调用函数采用明确 系列 , type ,或 proto 自变量。这仅影响 Python 如何表示,如返回值是 socket.getpeername() 而不是实际 OS 资源。不像 socket.fromfd() , fileno 将返回相同套接字而不是复制套接字。这可能有助于关闭分离套接字使用 socket.close() .

新近创建的套接字 不可继承 .

引发 审计事件 socket.__new__ 采用自变量 self , family , type , protocol .

3.3 版改变: 添加 AF_CAN 系列。添加 AF_RDS 系列。

3.4 版改变: 添加 CAN_BCM 协议。

3.4 版改变: 返回套接字现在不可继承。

3.7 版改变: 添加 CAN_ISOTP 协议。

3.7 版改变: SOCK_NONBLOCK or SOCK_CLOEXEC 位标志应用于 type 它们被清零,和 socket.type 将不反射它们。它们仍被传递给底层系统 socket() 调用。因此,

sock = socket.socket(
    socket.AF_INET,
    socket.SOCK_STREAM | socket.SOCK_NONBLOCK)
													

仍将创建非阻塞套接字当 OS 支持 SOCK_NONBLOCK ,但 sock.type 会被设为 socket.SOCK_STREAM .

3.9 版改变: 添加 CAN_J1939 协议。

socket. socketpair ( [ 系列 [ , type [ , proto ] ] ] )

Build a pair of connected socket objects using the given address family, socket type, and protocol number. Address family, socket type, and protocol number are as for the socket() function above. The default family is AF_UNIX if defined on the platform; otherwise, the default is AF_INET .

新近创建的套接字 不可继承 .

3.2 版改变: 返回套接字对象现在支持整个套接字 API,而不是子集。

3.4 版改变: 返回的套接字现在不可继承。

3.5 版改变: 添加 Windows 支持。

socket. create_connection ( address [ , timeout [ , source_address ] ] )

Connect to a TCP service listening on the Internet address (2 元组 (host, port) ), and return the socket object. This is a higher-level function than socket.connect() : if host is a non-numeric hostname, it will try to resolve it for both AF_INET and AF_INET6 , and then try to connect to all possible addresses in turn until a connection succeeds. This makes it easy to write clients that are compatible to both IPv4 and IPv6.

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() 被使用。

若供给, source_address 必须是 2 元组 (host, port) for the socket to bind to as its source address before connecting. If host or port are ‘’ or 0 respectively the OS default behavior will be used.

3.2 版改变: source_address 被添加。

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

方便函数将创建 TCP 套接字绑定到 address (2 元组 (host, port) ) 并返回套接字对象。

系列 应该为 AF_INET or AF_INET6 . backlog is the queue size passed to socket.listen() ; when 0 a default reasonable value is chosen. reuse_port dictates whether to set the SO_REUSEPORT socket option.

dualstack_ipv6 is true and the platform supports it the socket will be able to accept both IPv4 and IPv6 connections, else it will raise ValueError . Most POSIX platforms and Windows are supposed to support this functionality. When this functionality is enabled the address returned by socket.getpeername() when an IPv4 connection occurs will be an IPv6 address represented as an IPv4-mapped IPv6 address. If dualstack_ipv6 is false it will explicitly disable this functionality on platforms that enable it by default (e.g. Linux). This parameter can be used in conjunction with has_dualstack_ipv6() :

import socket
addr = ("", 8080)  # all interfaces, port 8080
if socket.has_dualstack_ipv6():
    s = socket.create_server(addr, family=socket.AF_INET6, dualstack_ipv6=True)
else:
    s = socket.create_server(addr)
												

注意

在 POSIX (便携式操作系统接口) 平台 SO_REUSEADDR socket option is set in order to immediately reuse previous sockets which were bound on the same address and remained in TIME_WAIT state.

3.8 版新增。

socket. has_dualstack_ipv6 ( )

返回 True if the platform supports creating a TCP socket which can handle both IPv4 and IPv6 connections.

3.8 版新增。

socket. fromfd ( fd , 系列 , type , proto=0 )

Duplicate the file descriptor fd (an integer as returned by a file object’s fileno() method) and build a socket object from the result. Address family, socket type and protocol number are as for the socket() function above. The file descriptor should refer to a socket, but this is not checked — subsequent operations on the object may fail if the file descriptor is invalid. This function is rarely needed, but can be used to get or set socket options on a socket passed to a program as standard input or output (such as a server started by the Unix inet daemon). The socket is assumed to be in blocking mode.

新近创建的套接字 不可继承 .

3.4 版改变: 返回套接字现在不可继承。

socket. fromshare ( data )

实例化套接字从获得数据来自 socket.share() 方法。假定套接字处于阻塞模式下。

可用性 :Windows。

3.3 版新增。

socket. SocketType

这是表示套接字对象类型的 Python 类型对象。如同 type(socket(...)) .

其它函数

socket 模块还提供各种网络相关服务:

socket. close ( fd )

关闭套接字文件描述符。这像 os.close() ,但用于套接字。在某些平台 (最显着的 Windows) os.close() 不工作于套接字文件描述符。

3.7 版新增。

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

翻译 host / port 自变量成 5 元组序列,包含创建连接到该服务的套接字的所有必要自变量。 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.

系列 , 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. flags argument can be one or several of the AI_* constants, and will influence how results are computed and returned. For example, AI_NUMERICHOST will disable domain name resolution and will raise an error if host is a domain name.

函数返回的 5 元组列表具有以下结构:

(family, type, proto, canonname, sockaddr)

在这些元组中, 系列 , type , proto are all integers and are meant to be passed to the socket() 函数。 canonname will be a string representing the canonical name of the host if AI_CANONNAME 属于 flags argument; else canonname will be empty. sockaddr is a tuple describing a socket address, whose format depends on the returned 系列 ( (address, port) 2-tuple for AF_INET (address, port, flowinfo, scope_id) 4-tuple for AF_INET6 ), and is meant to be passed to the socket.connect() 方法。

引发 审计事件 socket.getaddrinfo 采用自变量 host , port , family , type , protocol .

The following example fetches address information for a hypothetical TCP connection to example.org on port 80 (results may differ on your system if IPv6 isn’t enabled):

>>> socket.getaddrinfo("example.org", 80, proto=socket.IPPROTO_TCP)
[(<AddressFamily.AF_INET6: 10>, <SocketType.SOCK_STREAM: 1>,
 6, '', ('2606:2800:220:1:248:1893:25c8:1946', 80, 0, 0)),
 (<AddressFamily.AF_INET: 2>, <SocketType.SOCK_STREAM: 1>,
 6, '', ('93.184.216.34', 80))]
												

3.2 版改变: 现在可以使用关键词自变量传递参数。

3.7 版改变: 对于 IPv6 多点播送地址,表示地址的字符串不会包含 %scope_id 部分。

socket. getfqdn ( [ name ] )

返回完全合格域名对于 name 。若 name 被省略或空,它被解释成本地主机。要找到完全合格名称,主机名返回通过 gethostbyaddr() 被校验,之后紧跟主机别名 (若可用)。第一名称包括选中句点。若没有完全合格的域名可用且 name 有提供,它将不变返回。若 name 为空或等于 '0.0.0.0' ,主机名来自 gethostname() 被返回。

socket. gethostbyname ( hostname )

将主机名翻译成 IPv4 地址格式。IPv4 地址被返回成字符串,譬如 '100.50.200.5' 。若主机名本身是 IPv4 地址,它将不变返回。见 gethostbyname_ex() 了解更完整接口。 gethostbyname() 不支持 IPv6 名称解析,和 getaddrinfo() 应该被使用而不是 IPv4/v6 双堆栈支持。

引发 审计事件 socket.gethostbyname 采用自变量 hostname .

socket. gethostbyname_ex ( hostname )

将主机名翻译成 IPv4 地址格式,扩展接口。返回 3 元组 (hostname, aliaslist, ipaddrlist) where hostname 是首要主机名响应给定 ip_address , aliaslist 是同一地址的备选主机名列表 (可能为空),和 ipaddrlist 是同一主机同一接口的 IPv4 地址列表 (经常但始终不是单个地址)。 gethostbyname_ex() 不支持 IPv6 名称解析,和 getaddrinfo() 应该被使用而不是 IPv4/v6 双堆栈支持。

引发 审计事件 socket.gethostbyname 采用自变量 hostname .

socket. gethostname ( )

返回包含 Python 解释器目前正在其中执行的机器主机名字符串。

引发 审计事件 socket.gethostname 不带自变量。

注意: gethostname() 不会始终返回完全合格的域名;使用 getfqdn() 为此。

socket. gethostbyaddr ( ip_address )

返回 3 元组 (hostname, aliaslist, ipaddrlist) where hostname 是首要主机名响应给定 ip_address , aliaslist 是同一地址的备选主机名列表 (可能为空),和 ipaddrlist 是同一主机同一接口的 IPv4/v6 地址列表 (很可能只包含单个地址)。要找到完全合格的域名,使用函数 getfqdn() . gethostbyaddr() 支持 IPv4 和 IPv6 两者。

引发 审计事件 socket.gethostbyaddr 采用自变量 ip_address .

socket. getnameinfo ( sockaddr , flags )

翻译套接字地址 sockaddr 成 2 元组 (host, port) 。取决于设置的 flags , the result can contain a fully-qualified domain name or numeric address representation in host . Similarly, port can contain a string port name or a numeric port number.

对于 IPv6 地址, %scope_id is appended to the host part if sockaddr contains meaningful scope_id . Usually this happens for multicast addresses.

了解更多信息关于 flags 可以翻阅 getnameinfo(3) .

引发 审计事件 socket.getnameinfo 采用自变量 sockaddr .

socket. getprotobyname ( protocolname )

翻译 Internet 协议名称 (例如, 'icmp' ) to a constant suitable for passing as the (optional) third argument to the socket() function. This is usually only needed for sockets opened in “raw” mode ( SOCK_RAW ); for the normal socket modes, the correct protocol is chosen automatically if the protocol is omitted or zero.

socket. getservbyname ( servicename [ , protocolname ] )

Translate an Internet service name and protocol name to a port number for that service. The optional protocol name, if given, should be 'tcp' or 'udp' , otherwise any protocol will match.

引发 审计事件 socket.getservbyname 采用自变量 servicename , protocolname .

socket. getservbyport ( port [ , protocolname ] )

Translate an Internet port number and protocol name to a service name for that service. The optional protocol name, if given, should be 'tcp' or 'udp' , otherwise any protocol will match.

引发 审计事件 socket.getservbyport 采用自变量 port , protocolname .

socket. ntohl ( x )

Convert 32-bit positive integers from network to host byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 4-byte swap operation.

socket. ntohs ( x )

Convert 16-bit positive integers from network to host byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 2-byte swap operation.

Deprecated since version 3.7: In case x does not fit in 16-bit unsigned integer, but does fit in a positive C int, it is silently truncated to 16-bit unsigned integer. This silent truncation feature is deprecated, and will raise an exception in future versions of Python.

socket. htonl ( x )

Convert 32-bit positive integers from host to network byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 4-byte swap operation.

socket. htons ( x )

Convert 16-bit positive integers from host to network byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 2-byte swap operation.

Deprecated since version 3.7: In case x does not fit in 16-bit unsigned integer, but does fit in a positive C int, it is silently truncated to 16-bit unsigned integer. This silent truncation feature is deprecated, and will raise an exception in future versions of Python.

socket. inet_aton ( ip_string )

Convert an IPv4 address from dotted-quad string format (for example, ‘123.45.67.89’) to 32-bit packed binary format, as a bytes object four characters in length. This is useful when conversing with a program that uses the standard C library and needs objects of type struct in_addr , which is the C type for the 32-bit packed binary this function returns.

inet_aton() also accepts strings with less than three dots; see the Unix manual page inet(3) 了解细节。

If the IPv4 address string passed to this function is invalid, OSError will be raised. Note that exactly what is valid depends on the underlying C implementation of inet_aton() .

inet_aton() does not support IPv6, and inet_pton() 应该被使用而不是 IPv4/v6 双堆栈支持。

socket. inet_ntoa ( packed_ip )

Convert a 32-bit packed IPv4 address (a 像字节对象 four bytes in length) to its standard dotted-quad string representation (for example, ‘123.45.67.89’). This is useful when conversing with a program that uses the standard C library and needs objects of type struct in_addr , which is the C type for the 32-bit packed binary data this function takes as an argument.

If the byte sequence passed to this function is not exactly 4 bytes in length, OSError 会被引发。 inet_ntoa() does not support IPv6, and inet_ntop() 应该被使用而不是 IPv4/v6 双堆栈支持。

3.5 版改变: 可写 像字节对象 现在被接受。

socket. inet_pton ( address_family , ip_string )

将 IP 地址从特定系列字符串格式,转换成打包二进制格式。 inet_pton() 很有用当库或网络协议调用对象的类型为 struct in_addr (类似 inet_aton() ) 或 struct in6_addr .

Supported values for address_family are currently AF_INET and AF_INET6 . If the IP address string ip_string is invalid, OSError will be raised. Note that exactly what is valid depends on both the value of address_family and the underlying implementation of inet_pton() .

可用性 :Unix (也许不是所有平台)、Windows。

3.4 版改变: 添加 Windows 支持

socket. inet_ntop ( address_family , packed_ip )

转换打包 IP 地址 ( 像字节对象 of some number of bytes) to its standard, family-specific string representation (for example, '7.10.0.5' or '5aef:2b::8' ). inet_ntop() is useful when a library or network protocol returns an object of type struct in_addr (类似 inet_ntoa() ) 或 struct in6_addr .

Supported values for address_family are currently AF_INET and AF_INET6 . If the bytes object packed_ip is not the correct length for the specified address family, ValueError 会被引发。 OSError is raised for errors from the call to inet_ntop() .

可用性 :Unix (也许不是所有平台)、Windows。

3.4 版改变: 添加 Windows 支持

3.5 版改变: 可写 像字节对象 现在被接受。

socket. CMSG_LEN ( 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.

可用性 :大多数 Unix 平台,其它可能平台。

3.3 版新增。

socket. CMSG_SPACE ( length )

返回所需缓冲大小对于 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.

Note that some systems might support ancillary data without providing this function. Also note that setting the buffer size using the results of this function may not precisely limit the amount of ancillary data that can be received, since additional data may be able to fit into the padding area.

可用性 :大多数 Unix 平台,其它可能平台。

3.3 版新增。

socket. getdefaulttimeout ( )

Return 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 .

socket. setdefaulttimeout ( timeout )

为新的套接字对象设置默认浮点超时 (以秒为单位)。当首次导入 socket 模块时,默认为 None 。见 settimeout() 了解可能的值及其各自的含义。

socket. sethostname ( name )

将机器的主机名设为 name 。这将引发 OSError 若没有足够权限。

引发 审计事件 socket.sethostname 采用自变量 name .

可用性 : Unix.

3.3 版新增。

socket. if_nameindex ( )

返回网络接口信息 (索引 int, 名称 str) 元组的列表。 OSError 若系统调用失败。

可用性 : Unix, Windows.

3.3 版新增。

3.8 版改变: 添加 Windows 支持。

注意

On Windows network interfaces have different names in different contexts (all names are examples):

  • UUID: {FB605B73-AAC2-49A6-9A2F-25416AEA0573}

  • name: ethernet_32770

  • friendly name: vEthernet (nat)

  • description: Hyper-V Virtual Ethernet Adapter

This function returns names of the second form from the list, ethernet_32770 in this example case.

socket. if_nametoindex ( if_name )

Return a network interface index number corresponding to an interface name. OSError if no interface with the given name exists.

可用性 : Unix, Windows.

3.3 版新增。

3.8 版改变: 添加 Windows 支持。

另请参阅

接口名称的名称文档化在 if_nameindex() .

socket. if_indextoname ( if_index )

Return a network interface name corresponding to an interface index number. OSError if no interface with the given index exists.

可用性 : Unix, Windows.

3.3 版新增。

3.8 版改变: 添加 Windows 支持。

另请参阅

接口名称的名称文档化在 if_nameindex() .

socket. send_fds ( sock , buffers , fds [ , flags [ , address ] ] )

Send the list of file descriptors fds over an AF_UNIX socket sock . fds parameter is a sequence of file descriptors. Consult sendmsg() 了解这些参数的文档编制。

可用性 :Unix 支持 sendmsg() and SCM_RIGHTS 机制。

3.9 版新增。

socket. recv_fds ( sock , bufsize , maxfds [ , flags ] )

接收直到 maxfds 文件描述符从 AF_UNIX socket sock 。返回 (msg, list(fds), flags, addr) 。请翻阅 recvmsg() 了解这些参数的文档编制。

可用性 :Unix 支持 recvmsg() and SCM_RIGHTS 机制。

3.9 版新增。

注意

Any truncated integers at the end of the list of file descriptors.

套接字对象

套接字对象拥有以下方法。除了 makefile() ,这些对应于适用于套接字的 Unix 系统调用。

3.2 版改变: 支持 上下文管理器 协议被添加。退出上下文管理器相当于调用 close() .

socket. accept ( )

接受连接。必须将套接字绑定到地址并监听连接。返回值是一对 (conn, address) where conn new 套接字对象用于发送和接收数据当连接上时,和 address 是绑定到连接另一端的套接字地址。

新近创建的套接字 不可继承 .

3.4 版改变: 套接字现在不可继承。

3.5 版改变: 若系统调用被中断且信号处理程序未引发异常,方法现在会重试系统调用而不是引发 InterruptedError 异常 (见 PEP 475 了解基本原理)。

socket. bind ( address )

将套接字绑定到 address 。套接字必须尚未绑定。(格式对于 address 从属地址族 — 见上文。)

引发 审计事件 socket.bind 采用自变量 self , address .

socket. close ( )

Mark the socket closed. The underlying system resource (e.g. a file descriptor) is also closed when all file objects from makefile() are closed. Once that happens, all future operations on the socket object will fail. The remote end will receive no more data (after queued data is flushed).

Sockets are automatically closed when they are garbage-collected, but it is recommended to close() them explicitly, or to use a with statement around them.

3.6 版改变: OSError 现在被引发若发生错误,当底层 close() 调用有做出。

注意

close() releases the resource associated with a connection but does not necessarily close the connection immediately. If you want to close the connection in a timely fashion, call shutdown() before close() .

socket. connect ( address )

连接到远程套接字在 address 。(格式对于 address 从属地址族 — 见上文。)

若连接被信号中断,则方法等待直到连接完成,或引发 socket.timeout 当超时时,若信号处理程序不引发异常且套接字被阻塞 (或超时)。对于非阻塞套接字,方法引发 InterruptedError 异常若连接被信号中断 (或通过信号处理程序引发异常)。

引发 审计事件 socket.connect 采用自变量 self , address .

3.5 版改变: 方法现在等待连接完成而不是引发 InterruptedError 异常若连接被信号中断,信号处理程序不引发异常且套接字被阻塞或超时 (见 PEP 475 了解基本原理)。

socket. connect_ex ( address )

connect(address) , but return an error indicator instead of raising an exception for errors returned by the C-level connect() call (other problems, such as “host not found,” can still raise exceptions). The error indicator is 0 if the operation succeeded, otherwise the value of the errno variable. This is useful to support, for example, asynchronous connects.

引发 审计事件 socket.connect 采用自变量 self , address .

socket. detach ( )

Put the socket object into closed state without actually closing the underlying file descriptor. The file descriptor is returned, and can be reused for other purposes.

3.2 版新增。

socket. dup ( )

复制套接字。

新近创建的套接字 不可继承 .

3.4 版改变: 套接字现在不可继承。

socket. fileno ( )

返回套接字的文件描述符 (小整数),或 -1 当故障时。这很有用采用 select.select() .

在 Windows,在可以使用文件描述符的地方不可以使用由此方法返回的小整数 (譬如 os.fdopen() )。Unix 没有这种局限性。

socket. get_inheritable ( )

获取 可继承标志 对于套接字的文件描述符或套接字的句柄: True if the socket can be inherited in child processes, False if it cannot.

3.4 版新增。

socket. getpeername ( )

Return the remote address to which the socket is connected. This is useful to find out the port number of a remote IPv4/v6 socket, for instance. (The format of the address returned depends on the address family — see above.) On some systems this function is not supported.

socket. getsockname ( )

Return the socket’s own address. This is useful to find out the port number of an IPv4/v6 socket, for instance. (The format of the address returned depends on the address family — see above.)

socket. getsockopt ( level , optname [ , buflen ] )

Return the value of the given socket option (see the Unix man page getsockopt(2) ). The needed symbolic constants ( SO_* etc.) are defined in this module. If buflen is absent, an integer option is assumed and its integer value is returned by the function. If buflen is present, it specifies the maximum length of the buffer used to receive the option in, and this buffer is returned as a bytes object. It is up to the caller to decode the contents of the buffer (see the optional built-in module struct for a way to decode C structures encoded as byte strings).

socket. getblocking ( )

返回 True 若套接字在阻塞模式下, False 若在非阻塞模式下。

这相当于校验 socket.gettimeout() == 0 .

3.7 版新增。

socket. gettimeout ( )

Return the timeout in seconds (float) associated with socket operations, or None if no timeout is set. This reflects the last call to setblocking() or settimeout() .

socket. ioctl ( control , option )
平台

Windows

ioctl() method is a limited interface to the WSAIoctl system interface. Please refer to the Win32 文档编制 了解更多信息。

在其它平台,一般 fcntl.fcntl() and fcntl.ioctl() 函数可以使用;它们接受套接字对象作为其第一自变量。

目前仅支持下列控制代码: SIO_RCVALL , SIO_KEEPALIVE_VALS ,和 SIO_LOOPBACK_FAST_PATH .

3.6 版改变: SIO_LOOPBACK_FAST_PATH 被添加。

socket. listen ( [ backlog ] )

Enable a server to accept connections. If backlog is specified, it must be at least 0 (if it is lower, it is set to 0); it specifies the number of unaccepted connections that the system will allow before refusing new connections. If not specified, a default reasonable value is chosen.

3.5 版改变: backlog 参数现为可选。

socket. makefile ( mode='r' , buffering=None , * , encoding=None , errors=None , newline=None )

返回 文件对象 关联套接字。准确返回类型从属给定自变量对于 makefile() . These arguments are interpreted the same way as by the built-in open() function, except the only supported mode values are 'r' (默认), 'w' and 'b' .

The socket must be in blocking mode; it can have a timeout, but the file object’s internal buffer may end up in an inconsistent state if a timeout occurs.

Closing the file object returned by makefile() won’t close the original socket unless all other file objects have been closed and socket.close() has been called on the socket object.

注意

在 Windows,像文件对象的创建通过 makefile() cannot be used where a file object with a file descriptor is expected, such as the stream arguments of subprocess.Popen() .

socket. recv ( bufsize [ , flags ] )

从套接字接收数据。返回值是表示收到数据的字节对象。一次接收的最大数据量的指定通过 bufsize 。见 Unix 手册页面 recv(2) 了解含义对于可选自变量 flags ;默认为 0。

注意

为与硬件和网络实际情况最佳匹配,值对于 bufsize 应该是相对小的 2 的幂,例如 4096。

3.5 版改变: 若系统调用被中断且信号处理程序未引发异常,方法现在会重试系统调用而不是引发 InterruptedError 异常 (见 PEP 475 了解基本原理)。

socket. recvfrom ( bufsize [ , flags ] )

从套接字接收数据。返回值是成对 (bytes, address) where bytes 是表示收到数据的字节对象和 address 是发送数据的套接字地址。见 Unix 手册页面 recv(2) 了解含义对于可选自变量 flags ;默认为 0。(格式对于 address 从属地址族 — 见上文。)

3.5 版改变: 若系统调用被中断且信号处理程序未引发异常,方法现在会重试系统调用而不是引发 InterruptedError 异常 (见 PEP 475 了解基本原理)。

3.7 版改变: 对于多点播送 IPv6 地址,第一项的 address 不包含 %scope_id 部分。为获得完整 IPv6 地址使用 getnameinfo() .

socket. recvmsg ( bufsize [ , ancbufsize [ , flags ] ] )

接收正常数据 (直到 bufsize 字节) 和辅助数据从套接字。 ancbufsize argument sets the size in bytes of the internal buffer used to receive the ancillary data; it defaults to 0, meaning that no ancillary data will be received. Appropriate buffer sizes for ancillary data can be calculated using CMSG_SPACE() or CMSG_LEN() , and items which do not fit into the buffer might be truncated or discarded. The flags argument defaults to 0 and has the same meaning as for recv() .

返回值是 4 元组: (data, ancdata, msg_flags, address) data 项是 bytes object holding the non-ancillary data received. The ancdata item is a list of zero or more tuples (cmsg_level, cmsg_type, cmsg_data) representing the ancillary data (control messages) received: cmsg_level and cmsg_type are integers specifying the protocol level and protocol-specific type respectively, and cmsg_data bytes object holding the associated data. The msg_flags item is the bitwise OR of various flags indicating conditions on the received message; see your system documentation for details. If the receiving socket is unconnected, address is the address of the sending socket, if available; otherwise, its value is unspecified.

在某些系统中, sendmsg() and recvmsg() can be used to pass file descriptors between processes over an AF_UNIX socket. When this facility is used (it is often restricted to SOCK_STREAM sockets), recvmsg() will return, in its ancillary data, items of the form (socket.SOL_SOCKET, socket.SCM_RIGHTS, fds) ,其中 fds bytes object representing the new file descriptors as a binary array of the native C int 类型。若 recvmsg() raises an exception after the system call returns, it will first attempt to close any file descriptors received via this mechanism.

Some systems do not indicate the truncated length of ancillary data items which have been only partially received. If an item appears to extend beyond the end of the buffer, recvmsg() will issue a RuntimeWarning , and will return the part of it which is inside the buffer provided it has not been truncated before the start of its associated data.

当系统支持 SCM_RIGHTS mechanism, the following function will receive up to maxfds file descriptors, returning the message data and a list containing the descriptors (while ignoring unexpected conditions such as unrelated control messages being received). See also sendmsg() .

import socket, array
def recv_fds(sock, msglen, maxfds):
    fds = array.array("i")   # Array of ints
    msg, ancdata, flags, addr = sock.recvmsg(msglen, socket.CMSG_LEN(maxfds * fds.itemsize))
    for cmsg_level, cmsg_type, cmsg_data in ancdata:
        if cmsg_level == socket.SOL_SOCKET and cmsg_type == socket.SCM_RIGHTS:
            # Append data, ignoring any truncated integers at the end.
            fds.frombytes(cmsg_data[:len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
    return msg, list(fds)
										

可用性 :大多数 Unix 平台,其它可能平台。

3.3 版新增。

3.5 版改变: 若系统调用被中断且信号处理程序未引发异常,方法现在会重试系统调用而不是引发 InterruptedError 异常 (见 PEP 475 了解基本原理)。

socket. recvmsg_into ( buffers [ , ancbufsize [ , flags ] ] )

Receive normal data and ancillary data from the socket, behaving as recvmsg() would, but scatter the non-ancillary data into a series of buffers instead of returning a new bytes object. The buffers argument must be an iterable of objects that export writable buffers (e.g. bytearray objects); these will be filled with successive chunks of the non-ancillary data until it has all been written or there are no more buffers. The operating system may set a limit ( sysconf() value SC_IOV_MAX ) on the number of buffers that can be used. The ancbufsize and flags 自变量有相同含义如 recvmsg() .

返回值是 4 元组: (nbytes, ancdata, msg_flags, address) ,其中 nbytes is the total number of bytes of non-ancillary data written into the buffers, and ancdata , msg_flags and address are the same as for recvmsg() .

范例:

>>> import socket
>>> s1, s2 = socket.socketpair()
>>> b1 = bytearray(b'----')
>>> b2 = bytearray(b'0123456789')
>>> b3 = bytearray(b'--------------')
>>> s1.send(b'Mary had a little lamb')
22
>>> s2.recvmsg_into([b1, memoryview(b2)[2:9], b3])
(22, [], 0, None)
>>> [b1, b2, b3]
[bytearray(b'Mary'), bytearray(b'01 had a 9'), bytearray(b'little lamb---')]
										

可用性 :大多数 Unix 平台,其它可能平台。

3.3 版新增。

socket. recvfrom_into ( buffer [ , nbytes [ , flags ] ] )

Receive data from the socket, writing it into buffer instead of creating a new bytestring. The return value is a pair (nbytes, address) where nbytes is the number of bytes received and address 是发送数据的套接字地址。见 Unix 手册页面 recv(2) 了解含义对于可选自变量 flags ;默认为 0。(格式对于 address 从属地址族 — 见上文。)

socket. recv_into ( buffer [ , nbytes [ , flags ] ] )

接收直到 nbytes bytes from the socket, storing the data into a buffer rather than creating a new bytestring. If nbytes is not specified (or 0), receive up to the size available in the given buffer. Returns the number of bytes received. See the Unix manual page recv(2) 了解含义对于可选自变量 flags ;默认为 0。

socket. send ( bytes [ , flags ] )

发送数据到套接字。套接字必须连接到远程套接字。可选 flags 自变量有相同含义如 recv() above. Returns the number of bytes sent. Applications are responsible for checking that all data has been sent; if only some of the data was transmitted, the application needs to attempt delivery of the remaining data. For further information on this topic, consult the 套接字编程怎么样 .

3.5 版改变: 若系统调用被中断且信号处理程序未引发异常,方法现在会重试系统调用而不是引发 InterruptedError 异常 (见 PEP 475 了解基本原理)。

socket. sendall ( bytes [ , flags ] )

发送数据到套接字。套接字必须连接到远程套接字。可选 flags 自变量有相同含义如 recv() above. Unlike send() , this method continues to send data from bytes until either all data has been sent or an error occurs. None is returned on success. On error, an exception is raised, and there is no way to determine how much data, if any, was successfully sent.

3.5 版改变: The socket timeout is no more reset each time data is sent successfully. The socket timeout is now the maximum total duration to send all data.

3.5 版改变: 若系统调用被中断且信号处理程序未引发异常,方法现在会重试系统调用而不是引发 InterruptedError 异常 (见 PEP 475 了解基本原理)。

socket. sendto ( bytes , address )
socket. sendto ( bytes , flags , address )

Send data to the socket. The socket should not be connected to a remote socket, since the destination socket is specified by address 。可选 flags 自变量有相同含义如 recv() above. Return the number of bytes sent. (The format of address 从属地址族 — 见上文。)

引发 审计事件 socket.sendto 采用自变量 self , address .

3.5 版改变: 若系统调用被中断且信号处理程序未引发异常,方法现在会重试系统调用而不是引发 InterruptedError 异常 (见 PEP 475 了解基本原理)。

socket. sendmsg ( buffers [ , ancdata [ , flags [ , address ] ] ] )

Send normal and ancillary data to the socket, gathering the non-ancillary data from a series of buffers and concatenating it into a single message. The buffers argument specifies the non-ancillary data as an iterable of 像字节对象 (如 bytes objects); the operating system may set a limit ( sysconf() value SC_IOV_MAX ) on the number of buffers that can be used. The ancdata argument specifies the ancillary data (control messages) as an iterable of zero or more tuples (cmsg_level, cmsg_type, cmsg_data) ,其中 cmsg_level and cmsg_type are integers specifying the protocol level and protocol-specific type respectively, and cmsg_data is a bytes-like object holding the associated data. Note that some systems (in particular, systems without CMSG_SPACE() ) might support sending only one control message per call. The flags argument defaults to 0 and has the same meaning as for send() 。若 address is supplied and not None , it sets a destination address for the message. The return value is the number of bytes of non-ancillary data sent.

The following function sends the list of file descriptors fds over an AF_UNIX socket, on systems which support the SCM_RIGHTS 机制。另请参阅 recvmsg() .

import socket, array
def send_fds(sock, msg, fds):
    return sock.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", fds))])
										

可用性 :大多数 Unix 平台,其它可能平台。

引发 审计事件 socket.sendmsg 采用自变量 self , address .

3.3 版新增。

3.5 版改变: 若系统调用被中断且信号处理程序未引发异常,方法现在会重试系统调用而不是引发 InterruptedError 异常 (见 PEP 475 了解基本原理)。

socket. sendmsg_afalg ( [ msg , ] * , op [ , iv [ , assoclen [ , flags ] ] ] )

专用版本的 sendmsg() for AF_ALG socket. Set mode, IV, AEAD associated data length and flags for AF_ALG socket.

可用性 : Linux >= 2.6.38.

3.6 版新增。

socket. sendfile ( file , offset=0 , count=None )

发送文件直到到达 EOF (文件末尾) 通过使用高性能 os.sendfile 并返回发送总字节数。 file 必须是以二进制模式打开的常规文件对象。若 os.sendfile 不可用 (如 Windows) 或 file 不是常规文件 send() will be used instead. offset tells from where to start reading the file. If specified, count is the total number of bytes to transmit as opposed to sending the file until EOF is reached. File position is updated on return or also in case of error in which case file.tell() can be used to figure out the number of bytes which were sent. The socket must be of SOCK_STREAM type. Non-blocking sockets are not supported.

3.5 版新增。

socket. set_inheritable ( inheritable )

设置 可继承标志 为套接字文件描述符 (或套接字句柄)。

3.4 版新增。

socket. setblocking ( flag )

设置套接字的阻塞或非阻塞模式:若 flag 为 False,套接字被设为非阻塞模式,否则被设为阻塞模式。

此方法为简写对于某些 settimeout() 调用:

  • sock.setblocking(True) 相当于 sock.settimeout(None)

  • sock.setblocking(False) 相当于 sock.settimeout(0.0)

3.7 版改变: 方法不再应用 SOCK_NONBLOCK 标志在 socket.type .

socket. settimeout ( value )

设置阻塞套接字操作的超时。 value 自变量可以是表示秒数的非负浮点数,或 None 。若给定非 0 值,后续套接字操作将引发 timeout 异常若超时周期 value 已消耗在操作完成之前。若给定 0,套接字将处于非阻塞模式下。若 None 被给定,套接字将处于阻塞模式下。

进一步信息,请翻阅 关于套接字超时的注意事项 .

3.7 版改变: 方法不再触发 SOCK_NONBLOCK 标志在 socket.type .

socket. setsockopt ( level , optname , value: int )
socket. setsockopt ( level , optname , value: buffer )
socket. setsockopt ( level , optname , None , optlen: int )

Set the value of the given socket option (see the Unix manual page setsockopt(2) ). The needed symbolic constants are defined in the socket 模块 ( SO_* etc.). The value can be an integer, None 像字节对象 representing a buffer. In the later case it is up to the caller to ensure that the bytestring contains the proper bits (see the optional built-in module struct for a way to encode C structures as bytestrings). When value 被设为 None , optlen argument is required. It’s equivalent to call setsockopt() C function with optval=NULL and optlen=optlen .

3.5 版改变: 可写 像字节对象 现在被接受。

3.6 版改变: 添加 setsockopt(level, optname, None, optlen: int) 形式。

socket. shutdown ( how )

Shut down one or both halves of the connection. If how is SHUT_RD , further receives are disallowed. If how is SHUT_WR , further sends are disallowed. If how is SHUT_RDWR , further sends and receives are disallowed.

socket. share ( process_id )

Duplicate a socket and prepare it for sharing with a target process. The target process must be provided with process_id . The resulting bytes object can then be passed to the target process using some form of interprocess communication and the socket can be recreated there using fromshare() . Once this method has been called, it is safe to close the socket since the operating system has already duplicated it for the target process.

可用性 :Windows。

3.3 版新增。

注意,没有方法 read() or write() ;使用 recv() and send() without flags 自变量代替。

Socket objects also have these (read-only) attributes that correspond to the values given to the socket 构造函数。

socket. 系列

套接字系列。

socket. type

套接字类型。

socket. proto

套接字协议。

关于套接字超时的注意事项

套接字对象可以处于 3 种模式之一:阻塞、非阻塞或超时。默认情况下,套接字始终以阻塞模式被创建,但可以改变这通过调用 setdefaulttimeout() .

  • 阻塞模式 , operations block until complete or the system returns an error (such as connection timed out).

  • 非阻塞模式 , operations fail (with an error that is unfortunately system-dependent) if they cannot be completed immediately: functions from the select can be used to know when and whether a socket is available for reading or writing.

  • 超时模式 , operations fail if they cannot be completed within the timeout specified for the socket (they raise a timeout exception) or if the system returns an error.

注意

At the operating system level, sockets in 超时模式 are internally set in non-blocking mode. Also, the blocking and timeout modes are shared between file descriptors and socket objects that refer to the same network endpoint. This implementation detail can have visible consequences if e.g. you decide to use the fileno() of a socket.

超时和 connect 方法

connect() operation is also subject to the timeout setting, and in general it is recommended to call settimeout() before calling connect() or pass a timeout parameter to create_connection() . However, the system network stack may also return a connection timeout error of its own regardless of any Python socket timeout setting.

超时和 accept 方法

getdefaulttimeout() 不是 None ,套接字的返回通过 accept() method inherit that timeout. Otherwise, the behaviour depends on settings of the listening socket:

  • 若监听套接字在 阻塞模式 或在 超时模式 , the socket returned by accept() 是在 阻塞模式 ;

  • 若监听套接字在 非阻塞模式 , whether the socket returned by accept() is in blocking or non-blocking mode is operating system-dependent. If you want to ensure cross-platform behaviour, it is recommended you manually override this setting.

范例

Here are four minimal example programs using the TCP/IP protocol: a server that echoes all data that it receives back (servicing only one client), and a client using it. Note that a server must perform the sequence socket() , bind() , listen() , accept() (possibly repeating the accept() to service more than one client), while a client only needs the sequence socket() , connect() . Also note that the server does not sendall() / recv() on the socket it is listening on but on the new socket returned by accept() .

前 2 范例仅支持 IPv4。

# Echo server program
import socket
HOST = ''                 # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen(1)
    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)
        while True:
            data = conn.recv(1024)
            if not data: break
            conn.sendall(data)
								
# Echo client program
import socket
HOST = 'daring.cwi.nl'    # The remote host
PORT = 50007              # The same port as used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    s.sendall(b'Hello, world')
    data = s.recv(1024)
print('Received', repr(data))
								

The next two examples are identical to the above two, but support both IPv4 and IPv6. The server side will listen to the first address family available (it should listen to both instead). On most of IPv6-ready systems, IPv6 will take precedence and the server may not accept IPv4 traffic. The client side will try to connect to the all addresses returned as a result of the name resolution, and sends traffic to the first one connected successfully.

# Echo server program
import socket
import sys
HOST = None               # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
s = None
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,
                              socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
    af, socktype, proto, canonname, sa = res
    try:
        s = socket.socket(af, socktype, proto)
    except OSError as msg:
        s = None
        continue
    try:
        s.bind(sa)
        s.listen(1)
    except OSError as msg:
        s.close()
        s = None
        continue
    break
if s is None:
    print('could not open socket')
    sys.exit(1)
conn, addr = s.accept()
with conn:
    print('Connected by', addr)
    while True:
        data = conn.recv(1024)
        if not data: break
        conn.send(data)
								
# Echo client program
import socket
import sys
HOST = 'daring.cwi.nl'    # The remote host
PORT = 50007              # The same port as used by the server
s = None
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
    af, socktype, proto, canonname, sa = res
    try:
        s = socket.socket(af, socktype, proto)
    except OSError as msg:
        s = None
        continue
    try:
        s.connect(sa)
    except OSError as msg:
        s.close()
        s = None
        continue
    break
if s is None:
    print('could not open socket')
    sys.exit(1)
with s:
    s.sendall(b'Hello, world')
    data = s.recv(1024)
print('Received', repr(data))
								

The next example shows how to write a very simple network sniffer with raw sockets on Windows. The example requires administrator privileges to modify the interface:

import socket
# the public network interface
HOST = socket.gethostbyname(socket.gethostname())
# create a raw socket and bind it to the public interface
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
s.bind((HOST, 0))
# Include IP headers
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
# receive all packages
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
# receive a package
print(s.recvfrom(65565))
# disabled promiscuous mode
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
								

The next example shows how to use the socket interface to communicate to a CAN network using the raw socket protocol. To use CAN with the broadcast manager protocol instead, open a socket with:

socket.socket(socket.AF_CAN, socket.SOCK_DGRAM, socket.CAN_BCM)
								

After binding ( CAN_RAW ) or connecting ( CAN_BCM ) the socket, you can use the socket.send() ,和 socket.recv() operations (and their counterparts) on the socket object as usual.

此最后范例可能要求特殊权限:

import socket
import struct
# CAN frame packing/unpacking (see 'struct can_frame' in <linux/can.h>)
can_frame_fmt = "=IB3x8s"
can_frame_size = struct.calcsize(can_frame_fmt)
def build_can_frame(can_id, data):
    can_dlc = len(data)
    data = data.ljust(8, b'\x00')
    return struct.pack(can_frame_fmt, can_id, can_dlc, data)
def dissect_can_frame(frame):
    can_id, can_dlc, data = struct.unpack(can_frame_fmt, frame)
    return (can_id, can_dlc, data[:can_dlc])
# create a raw socket and bind it to the 'vcan0' interface
s = socket.socket(socket.AF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
s.bind(('vcan0',))
while True:
    cf, addr = s.recvfrom(can_frame_size)
    print('Received: can_id=%x, can_dlc=%x, data=%s' % dissect_can_frame(cf))
    try:
        s.send(cf)
    except OSError:
        print('Error sending CAN frame')
    try:
        s.send(build_can_frame(0x01, b'\x01\x02\x03'))
    except OSError:
        print('Error sending CAN frame')
								

Running an example several times with too small delay between executions, could lead to this error:

OSError: [Errno 98] Address already in use
								

This is because the previous execution has left the socket in a TIME_WAIT state, and can’t be immediately reused.

There is a socket flag to set, in order to prevent this, socket.SO_REUSEADDR :

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
								

SO_REUSEADDR flag tells the kernel to reuse a local socket in TIME_WAIT state, without waiting for its natural timeout to expire.

另请参阅

有关套接字编程 (在 C 中) 的介绍,见以下论文:

  • An Introductory 4.3BSD Interprocess Communication Tutorial , by Stuart Sechrest

  • An Advanced 4.3BSD Interprocess Communication Tutorial , by Samuel J. Leffler et al,

both in the UNIX Programmer’s Manual, Supplementary Documents 1 (sections PS1:7 and PS1:8). The platform-specific reference material for the various socket-related system calls are also a valuable source of information on the details of socket semantics. For Unix, refer to the manual pages; for Windows, see the WinSock (or Winsock 2) specification. For IPv6-ready APIs, readers may want to refer to RFC 3493 titled Basic Socket Interface Extensions for IPv6.