18.1. socket — 底层网络接口

S源代码: Lib/socket.py

这个模块提供访问BSD 套接字(socket) 的接口。它适用于所有现代Unix系统,Windows,MacOs及其他可能的平台。

注意

由于某些调用使用了操作系统的socket APIs,一些特性是依赖于特定平台的。

这个Python接口直接将套接字的Unix系统调用和库接口翻译成Python的面向对象风格:socket() 函数返回一个 socket 对象,这个对象的方法实现了不同的套接字系统调用。其中,一些参数类型比对应的C接口更高级:如对Python文件对象的 read()write() 操作,接收操作中缓冲区分配是自动的, 发送操作中缓冲区长度是隐含的。

另请参阅

socketserver模块
简化写作网络服务器的类。
ssl模块
套接字对象的 TLS/SSL 封装。

18.1.1. Socket 协议族

该模块支持何种socket协议族取决于系统与编译选项。

当一个socket对象被创建时,该socket对象所需的地址格式会根据特定的地址族被自动选择。Socket 地址被表示为:

  • 一个绑定到文件系统节点的 AF_UNIX 套接字的地址被表示为一个字符串,这个字符串使用文件系统编码与 'surrogateescape' 错误处理器 (see PEP 383).一个Linux抽象命名空间中的地址被作为一个被初始化为空字节的bytes-like object 返回;注意命名空间中的这些地址可以与常规文件系统套接字通讯,因此打算运行在Linux上的程序需要能同时处理两种类型的地址。当作为个一参数传递时,一个字符串或类字节对象可以被用做任意类型的地址。

    3.3 版本中的更改︰ AF_UNIX 套接字路径先前均假定使用 utf-8 编码。

    3.5 版本中的更改︰ 现在接受可写入的 bytes-like object

  • 一对参数 (host, port)用于 AF_INET 地址族, 其中host是一个字符串,表示在internet中像 'daring.cwi.nl'这样的域名 或 像'100.50.200.5'这样的IPv4地址, port(端口)参数是一个整数.

  • 对于 AF_INET6 地址族, 一个地址被表示为一个四维元组 (host, port, flowinfo, scopeid) , 其中, flowinfoscopeid 分别代表C中struct sockaddr_in6结构体中的成员 sin6_flowinfosin6_scope_id 。 为了向后兼容,在 socket 模块的方法中, flowinfoscopeid 参数可以被省略。但是请注意,忽略 scopeid 参数会导致操作IPv6地址时出现问题。

  • AF_NETLINK 套接字被表示为一个二维元组 (pid, groups).

  • 只有 Linux 支持的 TIPC 需要使用 AF_TIPC 地址族。TIPC 是一个开放的、基于非 IP 的、为 在集群计算机环境中使用而设计的网络协议。地址由表示成一个元组,元祖字段取决于地址类型。一般的元组形式是 (addr_type, v1、 v2、 v3 [, scope]),其中︰

    • addr_typeTIPC_ADDR_NAMESEQTIPC_ADDR_NAMETIPC_ADDR_ID中的一个。

    • scopeTIPC_ZONE_SCOPETIPC_CLUSTER_SCOPETIPC_NODE_SCOPE 中的一个。

    • 如果 addr_typeTIPC_ADDR_NAME,那么 v1 是服务器类型、 v2 是端口标识符,v3 应为 0。

      如果 addr_typeTIPC_ADDR_NAMESEQ,那么 v1 是服务器类型、 v2 是下级端口号, v3 是上级端口号。

      如果 addr_typeTIPC_ADDR_ID,那么v1 是节点,v2 是引用,v3 应该设置为 0。

  • 一个元组 (interface, ) 用于 AF_CAN 地址族, interface 是一个表示成像 'can0' 的网络接口名称的字符串。网络接口名称 ‘’ 可以用来接收这个地址族的所有网络接口的数据包。

  • 一个字符串或一个元组 (id, unit) 用于 PF_SYSTEM 族的 SYSPROTO_CONTROL 协议。内核管理的字符串名称是动态分配的ID。如果内核管理的ID和unit号已知或者使用已注册ID,那么元祖可以被使用。

    3.3 版本中新加入。

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

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

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

    • BTPROTO_HCI accepts (device_id,) where device_id is either an integer or a string with the Bluetooth address of the interface. (This depends on your OS; NetBSD and DragonFlyBSD expect a Bluetooth address while everything else expects an integer.)

      Changed in version 3.2: NetBSD and DragonFlyBSD support added.

    • BTPROTO_SCO accepts bdaddr where bdaddr is a bytes object containing the Bluetooth address in a string format. (ex. b'12:23:34:45:56:67') This protocol is not supported under FreeBSD.

  • Certain other address families (AF_PACKET, AF_CAN) support specific representations.

在表示IPv4地址时,可以采用两种特殊的字符串形式来表示特定的主机地址:用空字符串表示INADDR_ANY;用字符串'<broadcast>'来表示INADDR_BROADCASTThis behavior is not compatible with IPv6, therefore, you may want to avoid these if you intend to support IPv6 with your Python programs.

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; starting from Python 3.3, errors related to socket or address semantics raise OSError or one of its subclasses (they used to raise socket.error).

通过setblocking()支持非阻塞模式。A generalization of this based on timeouts is supported through settimeout().

18.1.2. 模块内容

模块socket导出以下元素。

18.1.2.1. 异常

exception socket.error

已弃用的OSError别名。

Changed in version 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中已更改:此类已成为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中已更改:此类已成为OSError的子类。

exception socket.timeout

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中已更改:此类已成为OSError的子类。

18.1.2.2. 常量

AF_* 和 SOCK_* 常量现在是 AddressFamilySocketKind IntEnum collections。

版本 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

这些常量表示套接字类型,用于 socket() 的第二个参数。根据系统的不同,可能会有更多常量。(似乎只有 SOCK_STREAMSOCK_DGRAM 广泛使用。)

socket.SOCK_CLOEXEC
socket.SOCK_NONBLOCK

这两个常量(如果已定义)可以与套接字类型结合使用,并允许你以原子方式设置一些标志(从而避免可能的竞争条件和需要单独调用)。

另请参见

安全文件描述符处理以获得更全面的解释。

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

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.

Availability: Linux >= 2.6.25.

New in version 3.3.

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.

Availability: Linux >= 2.6.25.

New in version 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.

This constant is documented in the Linux documentation.

Availability: Linux >= 3.6.

New in version 3.5.

socket.AF_RDS
socket.PF_RDS
socket.SOL_RDS
RDS_*

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

Availability: Linux >= 2.6.30.

New in version 3.3.

SIO_*
RCVALL_*

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

TIPC_*

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

Availability: 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.

18.1.2.3. 功能函数

18.1.2.3.1. 创建 sockets

以下函数都可以创建socket 对象.

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

使用给定的地址族、套接字类型和协议号创建一个新的套接字。地址族应当为 AF_INET(默认)、 AF_INET6AF_UNIXAF_CANAF_RDS套接字类型应该为 SOCK_STREAM(默认)、SOCK_DGRAMSOCK_RAW 或者其它某一个SOCK_ 常量。协议号通常为零并可以省略,在地址族为 AF_CAN 的情况下,协议号应该是 CAN_RAWCAN_BCM 之一。如果指定了 fileno,则忽略其它参数,从而返回具有指定文件描述符的套接字。socket.fromfd() 不同,fileno 将返回相同的套接字而不是复制一个。这可能有助于使用 socket.close() 关闭分离的套接字。

新创建的套接字是不可继承的

在版本3.3中更改:添加了 AF_CAN 地址族。添加 AF_RDS 地址族。

版本3.4中更改:添加了 CAN_BCM 协议。

在版本3.4中更改:返回的套接字现在是不可继承的。

socket.socketpair([family[, type[, proto]]])

使用所给的地址族,套接字类型和协议号创建一对已连接的socket 对象.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.

The newly created sockets are non-inheritable.

Changed in version 3.2: The returned socket objects now support the whole socket API, rather than a subset.

Changed in version 3.4: The returned sockets are now non-inheritable.

Changed in version 3.5: Windows support added.

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

连接到监听网络地址(一个2-tuple(host,port)),然后返回`socket`对象。这是比`socket.connect()`更高级的函数:如果`host`是非数字主机名,它将尝试为`AF_INET`和`AF_INET6`解析它,然后尝试依次连接到所有可能的地址,直到连接成功。 这使得编写兼容`IPv4`和`IPv6`的客户端变得容易。 连接到监听网络地址(一个2-tuple(host,port)),然后返回`socket`对象。这是比`socket.connect()`更高级的函数:如果`host`是非数字主机名,它将尝试为`AF_INET`和`AF_INET6`解析它,然后尝试依次连接到所有可能的地址,直到连接成功。 这使得编写兼容`IPv4`和`IPv6`的客户端变得容易。

尝试连接之前,传递可选的`timeout`参数将在`socket`实例上设置超时。 如果未提供超时,则使用由`getdefaulttimeout()`返回的全局默认超时设置。

如果提供,则在连接之前,`source_address`必须是`socket`绑定到的源地址的`2元组(主机,端口)`。 如果主机或端口分别为“”或0,则将使用操作系统默认行为。

Changed in version 3.2: source_address was added.

socket.fromfd(fd, family, type, proto=0)

复制文件描述符fd(由文件对象的fileno()方法返回的整数),并根据结果构建一个套接字对象。 地址族,套接字类型和协议号与上面的socket()函数一样。 文件描述符应该引用一个socket,但这不会被检查 - 如果文件描述符无效,对象的后续操作可能会失败。 这个函数很少用,但可以用来在传递给程序的套接字上获取或设置套接字选项作为标准输入或输出(例如由Unix inet守护进程启动的服务器)。 假设socket处于阻塞模式。

The newly created socket is non-inheritable.

Changed in version 3.4: The returned socket is now non-inheritable.

socket.fromshare(data)

使用从`socket.share()`方法获得的数据实例化一个socket. 假设socket处于阻塞模式

Availability: Windows.

New in version 3.3.

socket.SocketType

这是一个代表socket对象类型的Python类型对象。它与`type(socket(...))`相同。

18.1.2.3.2. 其它函数

socket 模块中同样也提供多种其他网络相关的服务:

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

host/port 参数转换为一个5元组序列,其中包含创建连接到该服务的套接字的所有必要参数。host 是一个域名,一个表示 IPv4/v6 地址的字符串或者为 Noneport 是一个表示服务名称的字符串例如'http'、一个表示端口号的数字或者为 None通过传递 None 作为 hostport 的值,可以将 NULL 传递给底层 C API。

可以选择指定 familytypeproto 参数,以缩小返回的地址列表。将零作为每个参数的值传递将选择全部结果。flags参数可以是 AI_* 常量中的一个或几个,并将影响如何计算和返回结果。例如,AI_NUMERICHOST将禁用域名解析,如果host是域名,则会引发错误。

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

(family, type, proto, canonname, sockaddr)

在这些元组中,familytypeproto 都是整数,用于传递给 socket() 函数。如果AI_CANONNAMEflags参数的一部分,canonname将是一个表示host的规范名称的字符串;否则canonname将为空。sockaddr 是一个描述套接字地址的元组,格式依赖于返回的 familyAF_INET(address, port) 2元组,AF_INET6(address, port, flow info, scope id) 4元组),用于传递给socket.connect() 方法。

以下示例在端口80上获取与example.org的假设TCP连接的地址信息(如果未启用IPv6,则系统上的结果可能不同):

>>> 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])

Return a fully qualified domain name for name. If name is omitted or empty, it is interpreted as the local host. To find the fully qualified name, the hostname returned by 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 by gethostname() is returned.

socket.gethostbyname(hostname)

将主机名转换为IPv4地址格式。IPv4地址以字符串形式返回,例如'100.50.200.5'如果主机名是IPv4地址本身,则返回不变。See gethostbyname_ex() for a more complete interface. gethostbyname() does not support IPv6 name resolution, and getaddrinfo() should be used instead for IPv4/v6 dual stack support.

socket.gethostbyname_ex(hostname)

Translate a host name to IPv4 address format, extended interface. Return a triple (hostname, aliaslist, ipaddrlist) where hostname is the primary host name responding to the given ip_address, aliaslist is a (possibly empty) list of alternative host names for the same address, and ipaddrlist is a list of IPv4 addresses for the same interface on the same host (often but not always a single address). gethostbyname_ex() does not support IPv6 name resolution, and getaddrinfo() should be used instead for IPv4/v6 dual stack support.

socket.gethostname()

Return a string containing the hostname of the machine where the Python interpreter is currently executing.

Note: gethostname() doesn’t always return the fully qualified domain name; use getfqdn() for that.

socket.gethostbyaddr(ip_address)

Return a triple (hostname, aliaslist, ipaddrlist) where hostname is the primary host name responding to the given ip_address, aliaslist is a (possibly empty) list of alternative host names for the same address, and ipaddrlist is a list of IPv4/v6 addresses for the same interface on the same host (most likely containing only a single address). To find the fully qualified domain name, use the function getfqdn(). gethostbyaddr() supports both IPv4 and IPv6.

socket.getnameinfo(sockaddr, flags)

Translate a socket address sockaddr into a 2-tuple (host, port). Depending on the settings of 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.

socket.getprotobyname(protocolname)

Translate an Internet protocol name (for example, '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.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)

将32位正整数从网络字节顺序转换为主机字节顺序。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) for details.

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() should be used instead for IPv4/v6 dual stack support.

socket.inet_ntoa(packed_ip)

Convert a 32-bit packed IPv4 address (a bytes-like object 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 will be raised. inet_ntoa() does not support IPv6, and inet_ntop() should be used instead for IPv4/v6 dual stack support.

Changed in version 3.5: Writable bytes-like object is now accepted.

socket.inet_pton(address_family, ip_string)

将IP地址从其特定类型的字符串格式转换为压缩的二进制格式。inet_pton() is useful when a library or network protocol calls for an object of type struct in_addr (similar to inet_aton()) or 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().

Availability: Unix (maybe not all platforms), Windows.

Changed in version 3.4: Windows support added

socket.inet_ntop(address_family, packed_ip)

Convert a packed IP address (a bytes-like object 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 (similar to inet_ntoa()) or 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 will be raised. OSError is raised for errors from the call to inet_ntop().

Availability: Unix (maybe not all platforms), Windows.

Changed in version 3.4: Windows support added

Changed in version 3.5: Writable bytes-like object is now accepted.

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.

Availability: most Unix platforms, possibly others.

New in version 3.3.

socket.CMSG_SPACE(length)

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

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.

New in version 3.3.

socket.getdefaulttimeout()

返回新套接字对象的默认超时值(以秒为单位)(浮点数)。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)

为新的套接字对象设置默认超时(以秒为单位)(float)。首次导入插槽模块时,默认值为None有关可能的值及其各自含义,请参见settimeout()

socket.sethostname(name)

将计算机的主机名设置为名称如果您没有足够的权限,则会引发OSError异常。

Availability: Unix.

New in version 3.3.

socket.if_nameindex()

Return a list of network interface information (index int, name string) tuples. OSError if the system call fails.

Availability: Unix.

New in version 3.3.

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.

Availability: Unix.

New in version 3.3.

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.

Availability: Unix.

New in version 3.3.

18.1.3. Socket 对象

Socket 对象有以下方法.Except for makefile(), these correspond to Unix system calls applicable to sockets.

Changed in version 3.2: Support for the context manager protocol was added. Exiting the context manager is equivalent to calling close().

socket.accept()

接收一个连接.该socket 必须要绑定一个地址和监听连接.The return value is a pair (conn, address) where conn is a new socket object usable to send and receive data on the connection, and address is the address bound to the socket on the other end of the connection.

The newly created socket is non-inheritable.

Changed in version 3.4: The socket is now non-inheritable.

Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).

socket.bind(address)

Bind the socket to address. 套接字必须尚未绑定。(The format of address depends on the address family — see above.)

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

套接字在被垃圾回收时自动关闭,但建议显式地close(),或者在打开套接字时使用with语句。

Note

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)

Connect to a remote socket at address. (The format of address depends on the address family — see above.)

If the connection is interrupted by a signal, the method waits until the connection completes, or raise a socket.timeout on timeout, if the signal handler doesn’t raise an exception and the socket is blocking or has a timeout. For non-blocking sockets, the method raises an InterruptedError exception if the connection is interrupted by a signal (or the exception raised by the signal handler).

Changed in version 3.5: The method now waits until the connection completes instead of raising an InterruptedError exception if the connection is interrupted by a signal, the signal handler doesn’t raise an exception and the socket is blocking or has a timeout (see the PEP 475 for the rationale).

socket.connect_ex(address)

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

New in version 3.2.

socket.dup()

Duplicate the socket.

The newly created socket is non-inheritable.

Changed in version 3.4: The socket is now non-inheritable.

socket.fileno()

Return the socket’s file descriptor (a small integer), or -1 on failure. This is useful with select.select().

Under Windows the small integer returned by this method cannot be used where a file descriptor can be used (such as os.fdopen()). Unix does not have this limitation.

socket.get_inheritable()

Get the inheritable flag of the socket’s file descriptor or socket’s handle: True if the socket can be inherited in child processes, False if it cannot.

New in version 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.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)
Platform:Windows

The ioctl() method is a limited interface to the WSAIoctl system interface. Please refer to the Win32 documentation for more information.

On other platforms, the generic fcntl.fcntl() and fcntl.ioctl() functions may be used; they accept a socket object as their first argument.

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.

Changed in version 3.5: The backlog parameter is now optional.

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

Return a file object associated with the socket. The exact returned type depends on the arguments given to makefile(). These arguments are interpreted the same way as by the built-in open() function, except the only supported mode values are 'r' (default), '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.

Note

On Windows, the file-like object created by 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])

从套接字接收数据。返回值是一个代表所收到的数据的字节对象。The maximum amount of data to be received at once is specified by bufsize. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero.

Note

For best match with hardware and network realities, the value of bufsize should be a relatively small power of 2, for example, 4096.

Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).

socket.recvfrom(bufsize[, flags])

Receive data from the socket. The return value is a pair (bytes, address) where bytes is a bytes object representing the data received and address is the address of the socket sending the data. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero. (The format of address depends on the address family — see above.)

Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).

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

Receive normal data (up to bufsize bytes) and ancillary data from the socket. The 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().

The return value is a 4-tuple: (data, ancdata, msg_flags, address). The data item is a 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 is a 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.

On some systems, 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), where fds is a bytes object representing the new file descriptors as a binary array of the native C int type. If 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.

On systems which support the 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.fromstring(cmsg_data[:len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
    return msg, list(fds)

Availability: most Unix platforms, possibly others.

New in version 3.3.

Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).

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 arguments have the same meaning as for recvmsg().

The return value is a 4-tuple: (nbytes, ancdata, msg_flags, address), where 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().

Example:

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

New in version 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 is the address of the socket sending the data. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero. (The format of address depends on the address family — see above.)

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

Receive up to 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) for the meaning of the optional argument flags; it defaults to zero.

socket.send(bytes[, flags])

socket插座必须连接到远程插座。The optional flags argument has the same meaning as for 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 Socket Programming HOWTO.

Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).

socket.sendall(bytes[, flags])

Send data to the socket. The socket must be connected to a remote socket. The optional flags argument has the same meaning as for 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.

Changed in version 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.

Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).

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. The optional flags argument has the same meaning as for recv() above. Return the number of bytes sent. (The format of address depends on the address family — see above.)

Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).

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-like objects (e.g. 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), where 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(). If 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 mechanism. See also 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.

New in version 3.3.

Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).

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

Send a file until EOF is reached by using high-performance os.sendfile and return the total number of bytes which were sent. file must be a regular file object opened in binary mode. If os.sendfile is not available (e.g. Windows) or file is not a regular 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.

New in version 3.5.

socket.set_inheritable(inheritable)

Set the inheritable flag of the socket’s file descriptor or socket’s handle.

New in version 3.4.

socket.setblocking(flag)

设置阻塞或非阻塞套接字模式t: 如果 flag 为假, 该套接字设置为无阻塞,否则成阻塞模式.:

此方法确切来说是 settimeout() 调用函数的简写形式:

  • sock.setblocking(True) 相当于 sock.settimeout(None)
  • sock.setblocking(False) 相当于 sock.settimeout(0.0)
socket.settimeout(value)

Set a timeout on blocking socket operations. The value argument can be a nonnegative floating point number expressing seconds, or None. If a non-zero value is given, subsequent socket operations will raise a timeout exception if the timeout period value has elapsed before the operation has completed. If zero is given, the socket is put in non-blocking mode. If None is given, the socket is put in blocking mode.

For further information, please consult the notes on socket timeouts.

socket.setsockopt(level, optname, value)

Set the value of the given socket option (see the Unix manual page setsockopt(2)). The needed symbolic constants are defined in the socket module (SO_* etc.). The value can be an integer or a bytes-like object 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 module struct for a way to encode C structures as bytestrings).

Changed in version 3.5: Writable bytes-like object is now accepted.

socket.shutdown(how)

Shut down one or both halves of the connection. 如果howSHUT_RD,则不允许进一步接收。如果howSHUT_WR,则不允许进一步发送。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.

Availability: Windows.

New in version 3.3.

Note that there are no methods read() or write(); use recv() and send() without flags argument instead.

Socket objects also have these (read-only) attributes that correspond to the values given to the socket constructor.

socket.family

The socket family.

socket.type

The socket type.

socket.proto

The socket protocol.

18.1.4. Notes on socket timeouts

A socket object can be in one of three modes: blocking, non-blocking, or timeout. Sockets are by default always created in blocking mode, but this can be changed by calling setdefaulttimeout().

  • In blocking mode, operations block until complete or the system returns an error (such as connection timed out).
  • In non-blocking mode, 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.
  • In timeout mode, 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.

Note

At the operating system level, sockets in timeout mode 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. Timeouts and the connect method

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

18.1.4.2. Timeouts and the accept method

If getdefaulttimeout() is not None, sockets returned by the accept() method inherit that timeout. Otherwise, the behaviour depends on settings of the listening socket:

  • if the listening socket is in blocking mode or in timeout mode, the socket returned by accept() is in blocking mode;
  • if the listening socket is in non-blocking mode, 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.

18.1.5. 示例

以下是使用TCP/IP协议的四个最小示例程序:一个回显收到的所有数据的服务器(仅为一个客户端提供服务),以及一个使用它的客户端。请注意,服务器必须顺序执行 socket()bind()listen()accept()(可能重复执行 accept() 以服务多个客户端),而客户端只需要顺序执行socket()connect()另请注意,服务器在它正在侦听的套接字上没有sendall()/recv(),而是在accept()返回的新套接字上。

前两个示例仅支持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))

接下来的两个示例与上面两个示例相同,但同时支持IPv4和IPv6。服务器端将监听可用的第一个地址族(其实它应该两者都监听)。在大多数支持IPv6的系统中,IPv6优先而且服务器可能不接受IPv4流量。客户端将尝试连接由于名称解析而返回的所有地址,并将流量发送到成功连接的第一个地址。

# 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))

下一个示例演示如何在Windows上使用原始套接字编写非常简单的网络嗅探器。该示例需要管理员权限才能修改接口:

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 the socket.send(), and the 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 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))

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

See also

For an introduction to socket programming (in C), see the following papers:

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