socket
— 低级网络接口
¶
此模块提供访问 BSD socket interface. It is available on all modern Unix systems, Windows, Mac OS X, BeOS, OS/2, and probably additional platforms.
注意
某些行为可能从属平台,由于调用的是操作系统的套接字 API。
For an introduction to socket programming (in C), see the following papers: An Introductory 4.3BSD Interprocess Communication Tutorial, by Stuart Sechrest and 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.
Python 接口是 Unix 系统调用和套接字库接口到 Python 面向对象风格的简明直译:
socket()
函数返回
套接字对象
其方法有实现各种套接字系统调用。参数类型比 C 接口中的要高级一些:如同采用
read()
and
write()
操作 Python 文件,接收操作的缓冲分配是自动的,而发送操作的缓冲长度是隐式的。
Socket addresses are represented as follows: A single string is used for the
AF_UNIX
address family. A pair
(host, port)
用于
AF_INET
地址族,其中
host
是以 Internet 域表示法表示主机名的字符串像
'daring.cwi.nl'
或 IPv4 地址像
'100.50.200.5'
,和
port
is an integer. For
AF_INET6
地址族 4 元组
(host, port, flowinfo,
scopeid)
的使用,其中
flowinfo
and
scopeid
表示
sin6_flowinfo
and
sin6_scope_id
member in
struct sockaddr_in6
在 C 中。对于
socket
模块方法,
flowinfo
and
scopeid
可以省略只为向后兼容。注意,不管怎样,省略
scopeid
can cause problems in manipulating scoped IPv6 addresses. Other address families are currently not supported. The address format required by a particular socket object is automatically selected based on the address family specified when the socket object was created.
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
. The behavior is not available for IPv6 for backward compatibility, therefore, you may want to avoid these if you intend to support IPv6 with your Python programs.
若使用主机名在 host 部分为 IPv4/v6 套接字地址,程序可能展示不确定行为,因为 Python 使用解析自 DNS 的第一返回地址。套接字地址将以不同方式被解析成实际 IPv4/v6 地址,取决于解析自 DNS 的结果和/或主机配置。对于确定性行为,使用数值地址在 host 部分。
New in version 2.5:
AF_NETLINK sockets are represented as pairs
pid, groups
.
2.6 版新增:
Linux-only support for TIPC is also available using the
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。
All errors raise exceptions. The normal exceptions for invalid argument types and out-of-memory conditions can be raised; errors related to socket or address semantics raise the error
socket.error
.
支持非阻塞模式透过
setblocking()
。支持基于超时的一般化透过
settimeout()
.
模块
socket
exports the following constants and functions:
socket.
error
¶
This exception is raised for socket-related errors. The accompanying value is either a string telling what went wrong or a pair
(errno, string)
representing an error returned by a system call, similar to the value accompanying
os.error
. See the module
errno
, which contains names for the error codes defined by the underlying operating system.
2.6 版改变:
socket.error
is now a child class of
IOError
.
socket.
herror
¶
This exception is raised for address-related errors, i.e. for functions that use
h_errno
in the C API, including
gethostbyname_ex()
and
gethostbyaddr()
.
The accompanying value is a pair
(h_errno, string)
表示由库调用返回的错误。
string
表示描述对于
h_errno
,如返回通过
hstrerror()
C 函数。
socket.
gaierror
¶
This exception is raised for address-related errors, for
getaddrinfo()
and
getnameinfo()
。伴随值是一对
(error, string)
表示由库调用返回的错误。
string
表示描述对于
error
,如返回通过
gai_strerror()
C function. The
error
值将匹配某一
EAI_*
常量 (在此模块中有定义)。
socket.
timeout
¶
This exception is raised when a timeout occurs on a socket which has had timeouts enabled via a prior call to
settimeout()
. The accompanying value is a string whose value is currently always “timed out”.
2.3 版新增。
socket.
AF_UNIX
¶
socket.
AF_INET
¶
socket.
AF_INET6
¶
这些常量表示地址 (和协议) 系列,用作第一自变量对于
socket()
。若
AF_UNIX
constant is not defined then this protocol is unsupported.
socket.
SOCK_STREAM
¶
socket.
SOCK_DGRAM
¶
socket.
SOCK_RAW
¶
socket.
SOCK_RDM
¶
socket.
SOCK_SEQPACKET
¶
这些常量表示套接字类型,用作第 2 自变量对于
socket()
. (Only
SOCK_STREAM
and
SOCK_DGRAM
似乎很有用,一般来说)。
SO_*
socket.
SOMAXCONN
¶
MSG_*
SOL_*
IPPROTO_*
IPPORT_*
INADDR_*
IP_*
IPV6_*
EAI_*
AI_*
NI_*
TCP_*
这些形式的很多常量,在有关套接字和/或 IP 协议的 Unix 文档编制中有文档化,在 socket 模块也有定义。它们一般是自变量用于
setsockopt()
and
getsockopt()
方法的套接字对象。在大多数情况下,在 Unix 头文件中有定义的那些符号才会被定义;对于少数符号,提供默认值。
SIO_*
RCVALL_*
用于 Windows WSAIoctl() 的常量。常量被用作为自变量对于
ioctl()
方法为套接字对象。
2.6 版新增。
TIPC_*
TIPC related constants, matching the ones exported by the C socket API. See the TIPC documentation for more information.
2.6 版新增。
socket.
has_ipv6
¶
此常量包含指示平台是否支持 IPv6 的布尔值。
2.3 版新增。
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.
传递可选
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.
2.6 版新增。
2.7 版改变: source_address 被添加。
socket.
getaddrinfo
(
host
,
port
[
,
系列
[
,
socktype
[
,
proto
[
,
flags
]
]
]
]
)
¶
翻译
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.
The
系列
,
socktype
and
proto
arguments can be optionally specified in order to narrow the list of addresses returned. By default, their value is
0
, meaning that the full range of results is selected. The
flags
argument can be one or several of the
AI_*
constants, and will influence how results are computed and returned. Its default value is
0
。例如,
AI_NUMERICHOST
will disable domain name resolution and will raise an error if
host
is a domain name.
函数返回的 5 元组列表具有以下结构:
(family, socktype, proto, canonname, sockaddr)
在这些元组中,
系列
,
socktype
,
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, flow info, scope id)
4-tuple for
AF_INET6
), and is meant to be passed to the
socket.connect()
方法。
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, 0, 0, socket.IPPROTO_TCP) [(10, 1, 6, '', ('2606:2800:220:1:248:1893:25c8:1946', 80, 0, 0)), (2, 1, 6, '', ('93.184.216.34', 80))]
2.2 版新增。
socket.
getfqdn
(
[
名称
]
)
¶
返回完全合格的域名对于
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 by
gethostname()
被返回。
2.0 版新增。
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 解释器目前正在其中执行的机器主机名字符串。
If you want to know the current machine’s IP address, you may want to use
gethostbyname(gethostname())
. This operation assumes that there is a valid address-to-host mapping for the host, and the assumption does not always hold.
注意:
gethostname()
不会始终返回完全合格的域名;使用
getfqdn()
(see above).
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
可以包含字符串端口名或数值端口号。
2.2 版新增。
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.
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.
socket
(
[
系列
[
,
type
[
,
proto
]
]
]
)
¶
使用给定地址族、套接字类型和协议编号,创建新的套接字。地址族应该是
AF_INET
(默认),
AF_INET6
or
AF_UNIX
。套接字类型应该是
SOCK_STREAM
(默认),
SOCK_DGRAM
或者或许某一其它
SOCK_
constants. The protocol number is usually zero and may be omitted in that case.
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
. Availability: Unix.
2.4 版新增。
socket.
fromfd
(
fd
,
系列
,
type
[
,
proto
]
)
¶
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. Availability: Unix.
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 string 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,
socket.error
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 string four characters 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 string passed to this function is not exactly 4 bytes in length,
socket.error
会被引发。
inet_ntoa()
does not support IPv6, and
inet_ntop()
应该被使用而不是 IPv4/v6 双堆栈支持。
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,
socket.error
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).
2.3 版新增。
socket.
inet_ntop
(
address_family
,
packed_ip
)
¶
Convert a packed IP address (a string of some number of characters) 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 string
packed_ip
is not the correct length for the specified address family,
ValueError
will be raised. A
socket.error
is raised for errors from the call to
inet_ntop()
.
Availability: Unix (maybe not all platforms).
2.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
.
2.3 版新增。
socket.
setdefaulttimeout
(
timeout
)
¶
Set the default timeout in seconds (float) for new socket objects. A value of
None
indicates that new socket objects have no timeout. When the socket module is first imported, the default is
None
.
2.3 版新增。
socket.
SocketType
¶
这是表示套接字对象类型的 Python 类型对象。如同
type(socket(...))
.
另请参阅
SocketServer
简化编写网络服务器的类。
ssl
套接字对象的 TLS/SSL 包裹器。
套接字对象拥有以下方法。除了
makefile()
these correspond to Unix system calls applicable to sockets.
socket.
accept
(
)
¶
接受连接。必须将套接字绑定到地址并监听连接。返回值是一对
(conn, address)
where
conn
是
new
套接字对象用于发送和接收数据当连接上时,和
address
是绑定到连接另一端的套接字地址。
socket.
bind
(
address
)
¶
将套接字绑定到 address 。套接字必须尚未绑定。(格式对于 address 从属地址族 — 见上文。)
注意
This method has historically accepted a pair of parameters for
AF_INET
addresses instead of only a tuple. This was never intentional and is no longer available in Python 2.0 and later.
socket.
close
(
)
¶
Close the socket. 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.
注意
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 从属地址族 — 见上文。)
注意
This method has historically accepted a pair of parameters for
AF_INET
addresses instead of only a tuple. This was never intentional and is no longer available in Python 2.0 and later.
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.
注意
This method has historically accepted a pair of parameters for
AF_INET
addresses instead of only a tuple. This was never intentional and is no longer available in Python 2.0 and later.
socket.
fileno
(
)
¶
Return the socket’s file descriptor (a small integer). This is useful with
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 string. 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 strings).
socket.
ioctl
(
控制
,
option
)
¶
Windows
The
ioctl()
method is a limited interface to the WSAIoctl system interface. Please refer to the
Win32 文档编制
了解更多信息。
在其它平台,一般
fcntl.fcntl()
and
fcntl.ioctl()
函数可以使用;它们接受套接字对象作为其第一自变量。
2.6 版新增。
socket.
listen
(
backlog
)
¶
监听套接字建立的连接。 backlog argument specifies the maximum number of queued connections and should be at least 0; the maximum value is system-dependent (usually 5), the minimum value is forced to 0.
socket.
makefile
(
[
mode
[
,
bufsize
]
]
)
¶
返回
文件对象
associated with the socket. (File objects are described in
文件对象
.) The file object does not close the socket explicitly when its
close()
method is called, but only removes its reference to the socket object, so that the socket will be closed if it is not referenced from anywhere else.
The socket must be in blocking mode (it can not have a timeout). The optional
mode
and
bufsize
arguments are interpreted the same way as by the built-in
file()
函数。
注意
在 Windows,像文件对象的创建通过
makefile()
无法使用若期望具有文件描述符的文件对象,譬如流自变量对于
subprocess.Popen()
.
socket.
recv
(
bufsize
[
,
flags
]
)
¶
Receive data from the socket. The return value is a string representing the data received. The maximum amount of data to be received at once is specified by bufsize 。见 Unix 手册页 recv(2) 了解含义对于可选自变量 flags ;默认为 0。
注意
为与硬件和网络实际情况最佳匹配,值对于 bufsize 应该是相对小的 2 的幂,例如 4096。
socket.
recvfrom
(
bufsize
[
,
flags
]
)
¶
从套接字接收数据。返回值是成对
(string, address)
where
string
is a string representing the data received and
address
是发送数据的套接字地址。见 Unix 手册页
recv(2)
了解含义对于可选自变量
flags
;默认为 0。(格式对于
address
从属地址族 — 见上文。)
socket.
recvfrom_into
(
buffer
[
,
nbytes
[
,
flags
]
]
)
¶
Receive data from the socket, writing it into
buffer
instead of creating a new string. The return value is a pair
(nbytes, address)
where
nbytes
is the number of bytes received and
address
是发送数据的套接字地址。见 Unix 手册页
recv(2)
了解含义对于可选自变量
flags
;默认为 0。(格式对于
address
从属地址族 — 见上文。)
2.5 版新增。
socket.
recv_into
(
buffer
[
,
nbytes
[
,
flags
]
]
)
¶
接收直到 nbytes bytes from the socket, storing the data into a buffer rather than creating a new string. 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。
2.5 版新增。
socket.
send
(
string
[
,
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 concept, consult the
套接字编程怎么样
.
socket.
sendall
(
string
[
,
flags
]
)
¶
发送数据到套接字。套接字必须连接到远程套接字。可选
flags
自变量有相同含义如
recv()
above. Unlike
send()
, this method continues to send data from
string
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.
socket.
sendto
(
string
,
address
)
¶
socket.
sendto
(
string
,
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.
setblocking
(
flag
)
¶
设置套接字的阻塞或非阻塞模式:若
flag
is 0, the socket is set to non-blocking, else to blocking mode. Initially all sockets are in blocking mode. In non-blocking mode, if a
recv()
call doesn’t find any data, or if a
send()
call can’t immediately dispose of the data, an
error
exception is raised; in blocking mode, the calls block until they can proceed.
s.setblocking(0)
相当于
s.settimeout(0.0)
;
s.setblocking(1)
相当于
s.settimeout(None)
.
socket.
settimeout
(
值
)
¶
设置阻塞套接字操作时的超时。
value
argument can be a nonnegative float expressing seconds, or
None
. If a float is given, subsequent socket operations will raise a
timeout
异常若超时周期
value
has elapsed before the operation has completed. Setting a timeout of
None
disables timeouts on socket operations.
s.settimeout(0.0)
相当于
s.setblocking(0)
;
s.settimeout(None)
相当于
s.setblocking(1)
.
2.3 版新增。
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()
.
2.3 版新增。
Some notes on socket blocking and timeouts: A socket object can be in one of three modes: blocking, non-blocking, or timeout. Sockets are always created in blocking mode. 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. In timeout mode, operations fail if they cannot be completed within the timeout specified for the socket or if the system returns an error. The
setblocking()
method is simply a shorthand for certain
settimeout()
调用。
Timeout mode internally sets the socket in non-blocking mode. The blocking and timeout modes are shared between file descriptors and socket objects that refer to the same network endpoint. A consequence of this is that file objects returned by the
makefile()
method must only be used when the socket is in blocking mode; in timeout or non-blocking mode file operations that cannot be completed immediately will fail.
注意,
connect()
operation is 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()
. The system network stack may return a connection timeout error of its own regardless of any Python socket timeout setting.
socket.
setsockopt
(
level
,
optname
,
值
)
¶
设置给定套接字选项的值 (见 Unix 手册页
setsockopt(2)
)。需要的符号常量的定义在
socket
模块 (
SO_*
etc.). The value can be an integer or a string representing a buffer. In the latter case it is up to the caller to ensure that the string contains the proper bits (see the optional built-in module
struct
for a way to encode C structures as strings).
socket.
shutdown
(
how
)
¶
关闭连接的一半 (或两半)。若
how
is
SHUT_RD
,禁止进一步接收。若
how
is
SHUT_WR
,禁止进一步发送。若
how
is
SHUT_RDWR
, further sends and receives are disallowed. Depending on the platform, shutting down one half of the connection can also close the opposite half (e.g. on Mac OS X,
shutdown(SHUT_WR)
does not allow further reads on the other end of the connection).
注意,没有方法
read()
or
write()
;使用
recv()
and
send()
without
flags
自变量代替。
套接字对象还有这些 (只读) 属性,给出值对应
socket
构造函数。
socket.
系列
¶
套接字系列。
2.5 版新增。
socket.
type
¶
套接字类型。
2.5 版新增。
socket.
proto
¶
套接字协议。
2.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 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 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not data: break conn.sendall(data) conn.close()
# Echo client program import socket HOST = 'daring.cwi.nl' # The remote host PORT = 50007 # The same port as used by the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) s.sendall('Hello, world') data = s.recv(1024) s.close() 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 socket.error as msg: s = None continue try: s.bind(sa) s.listen(1) except socket.error as msg: s.close() s = None continue break if s is None: print 'could not open socket' sys.exit(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close()
# 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 socket.error as msg: s = None continue try: s.connect(sa) except socket.error as msg: s.close() s = None continue break if s is None: print 'could not open socket' sys.exit(1) s.sendall('Hello, world') data = s.recv(1024) s.close() print 'Received', repr(data)
The last 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)
Running an example several times with too small delay between executions, could lead to this error:
socket.error: [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.
有
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_REUSEADDR
flag tells the kernel to reuse a local socket in
TIME_WAIT
state, without waiting for its natural timeout to expire.