socket
— 低级网络接口
¶
源代码: Lib/socket.py
此模块提供访问 BSD socket 接口。它可用于所有现代 Unix 系统、Windows、MacOS 及可能的其它平台。
注意
某些行为可能从属平台,由于调用的是操作系统的套接字 API。
Python 接口是 Unix 系统调用和套接字库接口到 Python 面向对象风格的简明直译:
socket()
函数返回
套接字对象
其方法有实现各种套接字系统调用。参数类型比 C 接口中的要高级一些:如同采用
read()
and
write()
操作 Python 文件,接收操作的缓冲分配是自动的,而发送操作的缓冲长度是隐式的。
另请参阅
socketserver
ssl
由此模块支持的各种套接字系列,从属系统和构建选项。
特定套接字对象要求的地址格式是基于指定地址族自动选择的,当创建套接字对象时。套接字地址表示如下:
一对
(host, port)
用于
AF_INET
地址族,其中
host
是以 Internet 域表示法表示主机名的字符串像
'daring.cwi.nl'
或 IPv4 地址像
'100.50.200.5'
,和
port
是整数。
For
AF_INET6
地址族 4 元组
(host, port, flowinfo,
scopeid)
的使用,其中
flowinfo
and
scopeid
表示
sin6_flowinfo
and
sin6_scope_id
成员在
struct sockaddr_in6
在 C 中。对于
socket
模块方法,
flowinfo
and
scopeid
可以省略只为向后兼容。注意,不管怎样,省略
scopeid
可能导致问题,当操纵 IPv6 作用域地址时。
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'
。网络接口名称
''
可以用于从此系列的所有网络接口接收数据包。
字符串或元组
(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 不支持此协议。
Certain other address families (
AF_PACKET
,
AF_CAN
) support specific representations.
For IPv4 addresses, two special forms are accepted instead of a host address: the empty string represents
INADDR_ANY
, and the string
'<broadcast>'
表示
INADDR_BROADCAST
。此行为不兼容 IPv6,因此,可能想要避免这些,若打算采用 Python 程序支持 IPv6。
若使用主机名在 host 部分为 IPv4/v6 套接字地址,程序可能展示不确定行为,因为 Python 使用解析自 DNS 的第一返回地址。套接字地址将以不同方式被解析成实际 IPv4/v6 地址,取决于解析自 DNS 的结果和/或主机配置。对于确定性行为,使用数值地址在 host 部分。
所有错误引发异常。可以引发正常异常,对于无效自变量类型和内存不足情况;从 Python 3.3 开始,与套接字或地址语义相关的错误会引发
OSError
或其子类之一 (它们用于引发
socket.error
).
支持非阻塞模式透过
setblocking()
。支持基于超时的一般化透过
settimeout()
.
模块
socket
导出下列元素。
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
.
socket.
gaierror
¶
子类化的
OSError
,此异常被引发对于地址相关错误通过
getaddrinfo()
and
getnameinfo()
。伴随值是一对
(error, string)
表示由库调用返回的错误。
string
表示描述对于
error
,如返回通过
gai_strerror()
C 函数。数值
error
值将匹配某一
EAI_*
常量 (在此模块中有定义)。
3.3 版改变:
此类是子类化的
OSError
.
socket.
timeout
¶
子类化的
OSError
,此异常被引发当已启用超时的套接字发生超时凭借先前调用
settimeout()
(或隐式透过
setdefaulttimeout()
)。伴随值是其值目前始终为 timed out 的字符串。
3.3 版改变:
此类是子类化的
OSError
.
AF_* 和 SOCK_* 常量现在是
AddressFamilyandSocketKindIntEnum集合。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_STREAMandSOCK_DGRAM似乎很有用,一般来说)。
socket.SOCK_CLOEXEC¶socket.SOCK_NONBLOCK¶若有定义这 2 常量,可以组合套接字类型并允许以原子方式设置一些标志 (从而避免可能的竞争条件和需要单独调用)。
另请参阅
安全文件描述符处理 了解更彻底解释。
Availability: Linux >= 2.6.27.
3.2 版新增。
SO_*socket.SOMAXCONN¶MSG_*SOL_*SCM_*IPPROTO_*IPPORT_*INADDR_*IP_*IPV6_*EAI_*AI_*NI_*TCP_*这些形式的很多常量,在有关套接字和/或 IP 协议的 Unix 文档编制中有文档化,在 socket 模块也有定义。它们一般是自变量用于
setsockopt()andgetsockopt()方法的套接字对象。在大多数情况下,在 Unix 头文件中有定义的那些符号才会被定义;对于少数符号,提供默认值。
socket.AF_CAN¶socket.PF_CAN¶SOL_CAN_*CAN_*Linux 文档编制有文档化这些形式的许多常量,在 socket 模块也有定义。
Availability: Linux >= 2.6.25.
3.3 版新增。
socket.CAN_BCM¶CAN_BCM_*CAN_BCM 属于 CAN 协议族,是 BCM (广播管理器) 协议。Linux 文档编制有文档化广播管理器常量,在 socket 模块也有定义。
Availability: Linux >= 2.6.25.
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 one must accept both CAN and CAN FD frames when reading from the socket.
此常量的文档化在 Linux 文档编制。
Availability: Linux >= 3.6.
3.5 版新增。
socket.AF_RDS¶socket.PF_RDS¶socket.SOL_RDS¶RDS_*Linux 文档编制有文档化这些形式的许多常量,在 socket 模块也有定义。
Availability: Linux >= 2.6.30.
3.3 版新增。
SIO_*RCVALL_*用于 Windows WSAIoctl() 的常量。常量被用作为自变量对于
ioctl()方法为套接字对象。
TIPC_*TIPC related constants, matching the ones exported by the C socket API. See the TIPC documentation for more information.
socket.AF_LINK¶Availability: BSD, OSX.
3.4 版新增。
socket.has_ipv6¶此常量包含指示平台是否支持 IPv6 的布尔值。
socket.BDADDR_ANY¶socket.BDADDR_LOCAL¶这些是包含具有特殊含义蓝牙地址的字符串常量。例如,
BDADDR_ANYcan be used to indicate any address when specifying the binding socket withBTPROTO_RFCOMM.
socket.HCI_FILTER¶socket.HCI_TIME_STAMP¶socket.HCI_DATA_DIR¶For use with
BTPROTO_HCI.HCI_FILTERis not available for NetBSD or DragonFlyBSD.HCI_TIME_STAMPandHCI_DATA_DIRare not available for FreeBSD, NetBSD, or DragonFlyBSD.18.1.2.3. 函数 ¶
18.1.2.3.1. 创建套接字 ¶
以下函数都创建 套接字对象 .
socket.socket( family=AF_INET , type=SOCK_STREAM , proto=0 , fileno=None ) ¶使用给定地址族、套接字类型和协议编号,创建新的套接字。地址族应该是
AF_INET(默认),AF_INET6,AF_UNIX,AF_CANorAF_RDS。套接字类型应该是SOCK_STREAM(默认),SOCK_DGRAM,SOCK_RAW或者或许某一其它SOCK_常量。协议编号通常为 0 且可以省略,或者若地址族为AF_CAN协议应为某一CAN_RAWorCAN_BCM。若 fileno is specified, the other arguments are ignored, causing the socket with the specified file descriptor to return. Unlikesocket.fromfd(), fileno 将返回相同套接字而不是复制套接字。这可能有助于关闭分离套接字使用socket.close().新近创建的套接字 不可继承 .
3.3 版改变: 添加 AF_CAN 系列。添加 AF_RDS 系列。
3.4 版改变: 添加 CAN_BCM 协议。
3.4 版改变: 返回套接字现在不可继承。
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 isAF_UNIXif defined on the platform; otherwise, the default isAF_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 thansocket.connect(): if host is a non-numeric hostname, it will try to resolve it for bothAF_INETandAF_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.传递可选 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.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 thesocket()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.share()方法。假定套接字处于阻塞模式下。可用性:Windows。
3.3 版新增。
socket.SocketType¶这是表示套接字对象类型的 Python 类型对象。如同
type(socket(...)).18.1.2.3.2. 其它函数 ¶
The
socket模块还提供各种网络相关服务:
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 orNone. By passingNoneas the value of host and port , you can passNULLto the underlying C API.The 系列 , 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. The flags argument can be one or several of the
AI_*constants, and will influence how results are computed and returned. For example,AI_NUMERICHOSTwill 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 ifAI_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 forAF_INET,(address, port, flow info, scope id)4-tuple forAF_INET6), and is meant to be passed to thesocket.connect()方法。The following example fetches address information for a hypothetical TCP connection to
example.orgon 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 版改变: 现在可以使用关键词自变量传递参数。
socket.getfqdn( [ name ] ) ¶返回完全合格的域名对于 name 。若 name 被省略或空,解释成本地主机。要找到完全合格的名称,主机名的返回通过
gethostbyaddr()is checked, followed by aliases for the host, if available. The first name which includes a period is selected. In case no fully qualified domain name is available, the hostname as returned bygethostname()被返回。
socket.gethostbyname( hostname ) ¶将主机名翻译成 IPv4 地址格式。IPv4 地址被返回成字符串,譬如
'100.50.200.5'。若主机名本身是 IPv4 地址,它将不变返回。见gethostbyname_ex()了解更完整接口。gethostbyname()不支持 IPv6 名称解析,和getaddrinfo()应该被使用而不是 IPv4/v6 双堆栈支持。
socket.gethostbyname_ex( hostname ) ¶将主机名翻译成 IPv4 地址格式,扩展接口。返回 3 元组
(hostname, aliaslist, ipaddrlist)where hostname 是首要主机名响应给定 ip_address , aliaslist 是同一地址的备选主机名列表 (可能为空),和 ipaddrlist 是同一主机同一接口的 IPv4 地址列表 (经常但始终不是单个地址)。gethostbyname_ex()不支持 IPv6 名称解析,和getaddrinfo()应该被使用而不是 IPv4/v6 双堆栈支持。
socket.gethostname( ) ¶返回包含 Python 解释器目前正在其中执行的机器主机名字符串。
注意:
gethostname()不会始终返回完全合格的域名;使用getfqdn()为此。
socket.gethostbyaddr( ip_address ) ¶返回 3 元组
(hostname, aliaslist, ipaddrlist)where hostname 是首要主机名响应给定 ip_address , aliaslist 是同一地址的备选主机名列表 (可能为空),和 ipaddrlist 是同一主机同一接口的 IPv4/v6 地址列表 (很可能只包含单个地址)。要找到完全合格的域名,使用函数getfqdn().gethostbyaddr()支持 IPv4 和 IPv6 两者。
socket.getnameinfo( sockaddr , flags ) ¶翻译套接字地址 sockaddr 成 2 元素元组
(host, port)。取决于设置的 flags , the result can contain a fully-qualified domain name or numeric address representation in host 。同样, port 可以包含字符串端口名或数值端口号。
socket.getprotobyname( protocolname ) ¶翻译 Internet 协议名称 (例如,
'icmp') to a constant suitable for passing as the (optional) third argument to thesocket()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.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.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.
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.
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,
OSErrorwill be raised. Note that exactly what is valid depends on the underlying C implementation ofinet_aton().
inet_aton()does not support IPv6, andinet_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, andinet_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_INETandAF_INET6. If the IP address string ip_string is invalid,OSErrorwill be raised. Note that exactly what is valid depends on both the value of address_family and the underlying implementation ofinet_pton().Availability: Unix (maybe not all platforms), 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 typestruct in_addr(类似inet_ntoa()) 或struct in6_addr.Supported values for address_family are currently
AF_INETandAF_INET6. If the bytes object packed_ip is not the correct length for the specified address family,ValueError会被引发。OSErroris raised for errors from the call toinet_ntop().Availability: Unix (maybe not all platforms), 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 useCMSG_SPACE()and thus include space for padding, even when the item will be the last in the buffer. RaisesOverflowErrorif length is outside the permissible range of values.Availability: most Unix platforms, possibly others.
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 theCMSG_SPACE()values for their associated data lengths. RaisesOverflowErrorif 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.
Availability: most Unix platforms, possibly others.
3.3 版新增。
socket.getdefaulttimeout( ) ¶Return the default timeout in seconds (float) for new socket objects. A value of
Noneindicates that new socket objects have no timeout. When the socket module is first imported, the default isNone.
socket.setdefaulttimeout( timeout ) ¶为新的套接字对象设置默认浮点超时 (以秒为单位)。当首次导入 socket 模块时,默认为
None。见settimeout()了解可能的值及其各自的含义。
socket.if_nametoindex( if_name ) ¶Return a network interface index number corresponding to an interface name.
OSErrorif no interface with the given name exists.可用性:Unix。
3.3 版新增。
socket.if_indextoname( if_index ) ¶Return a network interface name corresponding to an interface index number.
OSErrorif no interface with the given index exists.可用性:Unix。
3.3 版新增。
18.1.3. 套接字对象 ¶
套接字对象拥有以下方法。除了
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.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 awithstatement around them.注意
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, callshutdown()beforeclose().
socket.connect( address ) ¶连接到远程套接字在 address 。(格式对于 address 从属地址族 — 见上文。)
若连接被信号中断,则方法等待直到连接完成,或引发
socket.timeout当超时时,若信号处理程序不引发异常且套接字被阻塞 (或超时)。对于非阻塞套接字,方法引发InterruptedError异常若连接被信号中断 (或通过信号处理程序引发异常)。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-levelconnect()call (other problems, such as “host not found,” can still raise exceptions). The error indicator is0if the operation succeeded, otherwise the value of theerrnovariable. This is useful to support, for example, asynchronous connects.
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.fileno( ) ¶返回套接字的文件描述符 (小整数),或 -1 当故障时。这很有用采用
select.select().在 Windows,在可以使用文件描述符的地方不可以使用由此方法返回的小整数 (譬如
os.fdopen())。Unix 没有这种局限性。
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 modulestructfor a way to decode C structures encoded as byte strings).
socket.gettimeout( ) ¶Return the timeout in seconds (float) associated with socket operations, or
Noneif no timeout is set. This reflects the last call tosetblocking()orsettimeout().
socket.ioctl( 控制 , option ) ¶
Platform: Windows The
ioctl()method is a limited interface to the WSAIoctl system interface. Please refer to the Win32 文档编制 了解更多信息。在其它平台,一般
fcntl.fcntl()andfcntl.ioctl()函数可以使用;它们接受套接字对象作为其第一自变量。
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 版改变: The backlog 参数现为可选。
socket.makefile( mode='r' , buffering=None , * , encoding=None , errors=None , newline=None ) ¶返回 文件对象 关联套接字。准确返回类型从属给定自变量对于
makefile()。这些自变量的解释方式如同内置open()函数,除了只支持 mode 值为'r'(默认),'w'and'b'.套接字必须在阻塞模式下;可以超时,但文件对象的内部缓冲可能最终处于不一致状态,若出现超时。
关闭文件对象的返回通过
makefile()不会关闭原始套接字,除非所有其它文件对象已关闭且socket.close()已在套接字对象中调用。注意
在 Windows,像文件对象的创建通过
makefile()无法使用若期望具有文件描述符的文件对象,譬如流自变量对于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 了解基本原理)。
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()orCMSG_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 forrecv().返回值是 4 元组:
(data, ancdata, msg_flags, address)。 data 项是bytesobject 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 是bytesobject 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()andrecvmsg()can be used to pass file descriptors between processes over anAF_UNIXsocket. When this facility is used (it is often restricted toSOCK_STREAMsockets),recvmsg()will return, in its ancillary data, items of the form(socket.SOL_SOCKET, socket.SCM_RIGHTS, fds),其中 fds 是bytesobject representing the new file descriptors as a binary array of the native Cint类型。若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 aRuntimeWarning, 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_RIGHTSmechanism, 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 alsosendmsg().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.fromstring(cmsg_data[:len(cmsg_data) - (len(cmsg_data) % fds.itemsize)]) return msg, list(fds)Availability: most Unix platforms, possibly others.
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.bytearrayobjects); 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()值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 forrecvmsg().范例:
>>> 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---')]Availability: most Unix platforms, possibly others.
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. Unlikesend(), this method continues to send data from bytes until either all data has been sent or an error occurs.Noneis 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 从属地址族 — 见上文。)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 像字节对象 (如
bytesobjects); the operating system may set a limit (sysconf()值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 withoutCMSG_SPACE()) might support sending only one control message per call. The flags argument defaults to 0 and has the same meaning as forsend()。若 address is supplied and notNone, 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_UNIXsocket, on systems which support theSCM_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))])Availability: most Unix platforms, possibly others.
3.3 版新增。
3.5 版改变: 若系统调用被中断且信号处理程序未引发异常,方法现在会重试系统调用而不是引发
InterruptedError异常 (见 PEP 475 了解基本原理)。
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 casefile.tell()can be used to figure out the number of bytes which were sent. The socket must be ofSOCK_STREAMtype. Non-blocking sockets are not supported.3.5 版新增。
socket.setblocking( flag ) ¶设置套接字的阻塞或非阻塞模式:若 flag 为 False,套接字被设为非阻塞模式,否则被设为阻塞模式。
此方法为简写对于某些
settimeout()调用:
sock.setblocking(True)相当于sock.settimeout(None)sock.setblocking(False)相当于sock.settimeout(0.0)
socket.settimeout( value ) ¶设置阻塞套接字操作时的超时。 value 自变量可以是表示秒数的非负浮点数,或
None。若给定非 0 值,后续套接字操作将引发timeout异常若超时周期 value 已消耗在操作完成之前。若给定 0,套接字将处于非阻塞模式下。若None被给定,套接字将处于阻塞模式下。进一步信息,请翻阅 关于套接字超时的注意事项 .
socket.setsockopt( level , optname , value ) ¶设置给定套接字选项的值 (见 Unix 手册页 setsockopt(2) )。需要的符号常量的定义在
socket模块 (SO_*etc.). The value can be an integer or a 像字节对象 representing a buffer. In the latter case it is up to the caller to ensure that the bytestring contains the proper bits (see the optional built-in modulestructfor a way to encode C structures as bytestrings).3.5 版改变: 可写 像字节对象 现接受。
socket.shutdown( how ) ¶关闭连接的一半 (或两半)。若 how is
SHUT_RD,禁止进一步接收。若 how isSHUT_WR,禁止进一步发送。若 how isSHUT_RDWR,禁止进一步发送和接收。
复制套接字,并准备与目标进程共享套接字。必须提供的目标进程具有 process_id 。然后,可以使用某种形式的进程间通信将结果字节对象传递给目标进程,且在那里可以重新创建套接字使用
fromshare()。一旦调用此方法,就可以安全关闭套接字,由于 OS 已为目标进程复制套接字。可用性:Windows。
3.3 版新增。
注意,没有方法
read()orwrite();使用recv()andsend()without flags 自变量代替。套接字对象还有这些 (只读) 属性,给出值对应
socket构造函数。
socket.系列¶套接字系列。
socket.type¶套接字类型。
socket.proto¶套接字协议。
18.1.4. 关于套接字超时的注意事项 ¶
套接字对象可以处于 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
selectcan 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
timeoutexception) 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.18.1.4.1. 超时和
connect方法 ¶The
connect()operation is also subject to the timeout setting, and in general it is recommended to callsettimeout()before callingconnect()or pass a timeout parameter tocreate_connection(). However, the system network stack may also return a connection timeout error of its own regardless of any Python socket timeout setting.18.1.4.2. 超时和
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 返回通过
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.18.1.5. 范例 ¶
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 theaccept()to service more than one client), while a client only needs the sequencesocket(),connect(). Also note that the server does notsendall()/recv()on the socket it is listening on but on the new socket returned byaccept().前 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 last 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 thesocket.send(),和socket.recv()operations (and their counterparts) on the socket object as usual.This example might require special privileges:
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 useThis is because the previous execution has left the socket in a
TIME_WAITstate, and can’t be immediately reused.有
socket标志要设置,为阻止此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))the
SO_REUSEADDRflag tells the kernel to reuse a local socket inTIME_WAITstate, 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.