socket
— 低階網路介面¶
原始碼:Lib/socket.py
這個模組提供了操作 BSDsocket 的介面。這在所有現代 Unix 系統、Windows、MacOS,以及一些其他平台上都可用。
備註
由於是呼叫作業系統的 socket API,某些行為可能會因平台而有所差異。
適用: not WASI.
此模組在 WebAssembly 平台上不起作用或無法使用。更多資訊請參閱WebAssembly 平台。
Python 的介面是將 Unix 的系統呼叫和 socket 函式庫介面直接轉換成 Python 的物件導向風格:socket()
函式會回傳一個socket 物件,這個物件的方法實作了各種 socket 系統呼叫。與 C 語言介面相比,參數型別較為高階:就像 Python 文件操作中的read()
和write()
一樣,接收操作時會自動分配緩衝區,而發送操作時的緩衝區長度則是隱含的。
也參考
socketserver
模組簡化編寫網路伺服器的類別。
ssl
模組對 socket 物件的 TLS/SSL 的包裝器 (wrapper)。
Socket 系列家族¶
Depending on the system and the build options, various socket familiesare supported by this module.
The address format required by a particular socket object is automaticallyselected based on the address family specified when the socket object wascreated. Socket addresses are represented as follows:
The address of an
AF_UNIX
socket bound to a file system nodeis represented as a string, using the file system encoding and the'surrogateescape'
error handler (seePEP 383). An address inLinux's abstract namespace is returned as abytes-like object withan initial null byte; note that sockets in this namespace cancommunicate with normal file system sockets, so programs intended torun on Linux may need to deal with both types of address. A string orbytes-like object can be used for either type of address whenpassing it as an argument.在 3.3 版的變更:Previously,
AF_UNIX
socket paths were assumed to use UTF-8encoding.在 3.5 版的變更:Writablebytes-like object is now accepted.
A pair
(host,port)
is used for theAF_INET
address family,wherehost is a string representing either a hostname in internet domainnotation like'daring.cwi.nl'
or an IPv4 address like'100.50.200.5'
,andport is an integer.For IPv4 addresses, two special forms are accepted instead of a hostaddress:
''
representsINADDR_ANY
, which is used to bind to allinterfaces, and the string'<broadcast>'
representsINADDR_BROADCAST
. This behavior is not compatible with IPv6,therefore, you may want to avoid these if you intend to support IPv6 with yourPython programs.
For
AF_INET6
address family, a four-tuple(host,port,flowinfo,scope_id)
is used, whereflowinfo andscope_id represent thesin6_flowinfo
andsin6_scope_id
members instructsockaddr_in6
in C. Forsocket
module methods,flowinfo andscope_id can be omitted just forbackward compatibility. Note, however, omission ofscope_id can cause problemsin manipulating scoped IPv6 addresses.在 3.7 版的變更:For multicast addresses (withscope_id meaningful)address may not contain
%scope_id
(orzoneid
) part. This information is superfluous and maybe safely omitted (recommended).AF_NETLINK
sockets are represented as pairs(pid,groups)
.Linux-only support for TIPC is available using the
AF_TIPC
address family. TIPC is an open, non-IP based networked protocol designedfor use in clustered computer environments. Addresses are represented by atuple, and the fields depend on the address type. The general tuple form is(addr_type,v1,v2,v3[,scope])
, where:addr_type is one of
TIPC_ADDR_NAMESEQ
,TIPC_ADDR_NAME
,orTIPC_ADDR_ID
.scope is one of
TIPC_ZONE_SCOPE
,TIPC_CLUSTER_SCOPE
, andTIPC_NODE_SCOPE
.Ifaddr_type is
TIPC_ADDR_NAME
, thenv1 is the server type,v2 isthe port identifier, andv3 should be 0.Ifaddr_type is
TIPC_ADDR_NAMESEQ
, thenv1 is the server type,v2is the lower port number, andv3 is the upper port number.Ifaddr_type is
TIPC_ADDR_ID
, thenv1 is the node,v2 is thereference, andv3 should be set to 0.
A tuple
(interface,)
is used for theAF_CAN
address family,whereinterface is a string representing a network interface name like'can0'
. The network interface name''
can be used to receive packetsfrom all network interfaces of this family.CAN_ISOTP
protocol require a tuple(interface,rx_addr,tx_addr)
where both additional parameters are unsigned long integer that represent aCAN identifier (standard or extended).CAN_J1939
protocol require a tuple(interface,name,pgn,addr)
where additional parameters are 64-bit unsigned integer representing theECU name, a 32-bit unsigned integer representing the Parameter Group Number(PGN), and an 8-bit integer representing the address.
A string or a tuple
(id,unit)
is used for theSYSPROTO_CONTROL
protocol of thePF_SYSTEM
family. The string is the name of akernel control using a dynamically assigned ID. The tuple can be used if IDand unit number of the kernel control are known or if a registered ID isused.在 3.3 版被加入.
AF_BLUETOOTH
supports the following protocols and addressformats:BTPROTO_L2CAP
accepts(bdaddr,psm)
wherebdaddr
isthe Bluetooth address as a string andpsm
is an integer.BTPROTO_RFCOMM
accepts(bdaddr,channel)
wherebdaddr
is the Bluetooth address as a string andchannel
is an integer.BTPROTO_HCI
accepts a format that depends on your OS.On Linux it accepts a tuple
(device_id,)
wheredevice_id
is an integer specifying the number of the Bluetooth device.On FreeBSD, NetBSD and DragonFly BSD it accepts
bdaddr
wherebdaddr
is the Bluetooth address as a string.
在 3.2 版的變更:加入對 NetBSD 和 DragonFlyBSD 的支援。
在 3.13.3 版的變更:新增對 FreeBSD 的支援。
BTPROTO_SCO
acceptsbdaddr
wherebdaddr
isthe Bluetooth address as a string or abytes
object.(ex.'12:23:34:45:56:67'
orb'12:23:34:45:56:67'
)This protocol is not supported under FreeBSD.
AF_ALG
is a Linux-only socket based interface to Kernelcryptography. An algorithm socket is configured with a tuple of two to fourelements(type,name[,feat[,mask]])
, where:type is the algorithm type as string, e.g.
aead
,hash
,skcipher
orrng
.name is the algorithm name and operation mode as string, e.g.
sha256
,hmac(sha256)
,cbc(aes)
ordrbg_nopr_ctr_aes256
.feat andmask are unsigned 32bit integers.
適用: Linux >= 2.6.38.
Some algorithm types require more recent Kernels.
在 3.6 版被加入.
AF_VSOCK
allows communication between virtual machines andtheir hosts. The sockets are represented as a(CID,port)
tuplewhere the context ID or CID and port are integers.在 3.7 版被加入.
AF_PACKET
is a low-level interface directly to network devices.The addresses are represented by the tuple(ifname,proto[,pkttype[,hatype[,addr]]])
where:ifname - String specifying the device name.
proto - The Ethernet protocol number.May be
ETH_P_ALL
to capture all protocols,one of theETHERTYPE_* constantsor any other Ethernet protocol number.pkttype - Optional integer specifying the packet type:
PACKET_HOST
(the default) - Packet addressed to the local host.PACKET_BROADCAST
- Physical-layer broadcast packet.PACKET_MULTICAST
- Packet sent to a physical-layer multicast address.PACKET_OTHERHOST
- Packet to some other host that has been caught bya device driver in promiscuous mode.PACKET_OUTGOING
- Packet originating from the local host that islooped back to a packet socket.
hatype - Optional integer specifying the ARP hardware address type.
addr - Optional bytes-like object specifying the hardware physicaladdress, whose interpretation depends on the device.
適用: Linux >= 2.2.
AF_QIPCRTR
is a Linux-only socket based interface for communicatingwith services running on co-processors in Qualcomm platforms. The addressfamily is represented as a(node,port)
tuple where thenode andportare non-negative integers.適用: Linux >= 4.7.
在 3.8 版被加入.
IPPROTO_UDPLITE
is a variant of UDP which allows you to specifywhat portion of a packet is covered with the checksum. It adds two socketoptions that you can change.self.setsockopt(IPPROTO_UDPLITE,UDPLITE_SEND_CSCOV,length)
willchange what portion of outgoing packets are covered by the checksum andself.setsockopt(IPPROTO_UDPLITE,UDPLITE_RECV_CSCOV,length)
willfilter out packets which cover too little of their data. In both caseslength
should be inrange(8,2**16,8)
.Such a socket should be constructed with
socket(AF_INET,SOCK_DGRAM,IPPROTO_UDPLITE)
for IPv4 orsocket(AF_INET6,SOCK_DGRAM,IPPROTO_UDPLITE)
for IPv6.適用: Linux >= 2.6.20, FreeBSD >= 10.1
在 3.9 版被加入.
AF_HYPERV
is a Windows-only socket based interface for communicatingwith Hyper-V hosts and guests. The address family is represented as a(vm_id,service_id)
tuple where thevm_id
andservice_id
areUUID strings.The
vm_id
is the virtual machine identifier or a set of known VMID valuesif the target is not a specific virtual machine. Known VMID constantsdefined onsocket
are:HV_GUID_ZERO
HV_GUID_BROADCAST
HV_GUID_WILDCARD
- Used to bind on itself and accept connections fromall partitions.HV_GUID_CHILDREN
- Used to bind on itself and accept connection fromchild partitions.HV_GUID_LOOPBACK
- Used as a target to itself.HV_GUID_PARENT
- When used as a bind accepts connection from the parentpartition. When used as an address target it will connect to the parent partition.
The
service_id
is the service identifier of the registered service.在 3.12 版被加入.
If you use a hostname in thehost portion of IPv4/v6 socket address, theprogram may show a nondeterministic behavior, as Python uses the first addressreturned from the DNS resolution. The socket address will be resolveddifferently into an actual IPv4/v6 address, depending on the results from DNSresolution and/or the host configuration. For deterministic behavior use anumeric address inhost portion.
All errors raise exceptions. The normal exceptions for invalid argument typesand out-of-memory conditions can be raised. Errorsrelated to socket or address semantics raiseOSError
or one of itssubclasses.
Non-blocking mode is supported throughsetblocking()
. Ageneralization of this based on timeouts is supported throughsettimeout()
.
模組內容¶
The modulesocket
exports the following elements.
例外¶
- exceptionsocket.herror¶
A subclass of
OSError
, this exception is raised foraddress-related errors, i.e. for functions that useh_errno in the POSIXC API, includinggethostbyname_ex()
andgethostbyaddr()
.The accompanying value is a pair(h_errno,string)
representing anerror returned by a library call.h_errno is a numeric value, whilestring represents the description ofh_errno, as returned by thehstrerror()
C function.在 3.3 版的變更:This class was made a subclass of
OSError
.
- exceptionsocket.gaierror¶
A subclass of
OSError
, this exception is raised foraddress-related errors bygetaddrinfo()
andgetnameinfo()
.The accompanying value is a pair(error,string)
representing an errorreturned by a library call.string represents the description oferror, as returned by thegai_strerror()
C function. Thenumericerror value will match one of theEAI_*
constantsdefined in this module.在 3.3 版的變更:This class was made a subclass of
OSError
.
- exceptionsocket.timeout¶
A deprecated alias of
TimeoutError
.A subclass of
OSError
, this exception is raised when a timeoutoccurs on a socket which has had timeouts enabled via a prior call tosettimeout()
(or implicitly throughsetdefaulttimeout()
). The accompanying value is a stringwhose value is currently always "timed out".在 3.3 版的變更:This class was made a subclass of
OSError
.在 3.10 版的變更:This class was made an alias of
TimeoutError
.
常數¶
The AF_* and SOCK_* constants are now
AddressFamily
andSocketKind
IntEnum
collections.在 3.4 版被加入.
- socket.AF_UNIX¶
- socket.AF_INET¶
- socket.AF_INET6¶
These constants represent the address (and protocol) families, used for thefirst argument to
socket()
. If theAF_UNIX
constant is notdefined then this protocol is unsupported. More constants may be availabledepending on the system.
- socket.AF_UNSPEC¶
AF_UNSPEC
means thatgetaddrinfo()
should return socket addresses for anyaddress family (either IPv4, IPv6, or any other) that can be used.
- socket.SOCK_STREAM¶
- socket.SOCK_DGRAM¶
- socket.SOCK_RAW¶
- socket.SOCK_RDM¶
- socket.SOCK_SEQPACKET¶
These constants represent the socket types, used for the second argument to
socket()
. More constants may be available depending on the system.(OnlySOCK_STREAM
andSOCK_DGRAM
appear to be generallyuseful.)
- socket.SOCK_CLOEXEC¶
- socket.SOCK_NONBLOCK¶
These two constants, if defined, can be combined with the socket types andallow you to set some flags atomically (thus avoiding possible raceconditions and the need for separate calls).
也參考
Secure File Descriptor Handlingfor a more thorough explanation.
適用: Linux >= 2.6.27.
在 3.2 版被加入.
- SO_*
- socket.SOMAXCONN¶
- MSG_*
- SOL_*
- SCM_*
- IPPROTO_*
- IPPORT_*
- INADDR_*
- IP_*
- IPV6_*
- EAI_*
- AI_*
- NI_*
- TCP_*
Many constants of these forms, documented in the Unix documentation on socketsand/or the IP protocol, are also defined in the socket module. They aregenerally used in arguments to the
setsockopt()
andgetsockopt()
methods of socket objects. In most cases, only those symbols that are definedin the Unix header files are defined; for a few symbols, default values areprovided.在 3.6 版的變更:
SO_DOMAIN
,SO_PROTOCOL
,SO_PEERSEC
,SO_PASSSEC
,TCP_USER_TIMEOUT
,TCP_CONGESTION
were added.在 3.6.5 版的變更:On Windows,
TCP_FASTOPEN
,TCP_KEEPCNT
appear if run-time Windowssupports.在 3.7 版的變更:新增
TCP_NOTSENT_LOWAT
。On Windows,
TCP_KEEPIDLE
,TCP_KEEPINTVL
appear if run-time Windowssupports.在 3.10 版的變更:
IP_RECVTOS
was added. AddedTCP_KEEPALIVE
. On MacOS this constant can be used in the same way thatTCP_KEEPIDLE
is used on Linux.在 3.11 版的變更:Added
TCP_CONNECTION_INFO
. On MacOS this constant can be used in thesame way thatTCP_INFO
is used on Linux and BSD.在 3.12 版的變更:Added
SO_RTABLE
andSO_USER_COOKIE
. On OpenBSDand FreeBSD respectively those constants can be used in the same way thatSO_MARK
is used on Linux. Also added missing TCP socket options fromLinux:TCP_MD5SIG
,TCP_THIN_LINEAR_TIMEOUTS
,TCP_THIN_DUPACK
,TCP_REPAIR
,TCP_REPAIR_QUEUE
,TCP_QUEUE_SEQ
,TCP_REPAIR_OPTIONS
,TCP_TIMESTAMP
,TCP_CC_INFO
,TCP_SAVE_SYN
,TCP_SAVED_SYN
,TCP_REPAIR_WINDOW
,TCP_FASTOPEN_CONNECT
,TCP_ULP
,TCP_MD5SIG_EXT
,TCP_FASTOPEN_KEY
,TCP_FASTOPEN_NO_COOKIE
,TCP_ZEROCOPY_RECEIVE
,TCP_INQ
,TCP_TX_DELAY
.AddedIP_PKTINFO
,IP_UNBLOCK_SOURCE
,IP_BLOCK_SOURCE
,IP_ADD_SOURCE_MEMBERSHIP
,IP_DROP_SOURCE_MEMBERSHIP
.在 3.13 版的變更:Added
SO_BINDTOIFINDEX
. On Linux this constant can be used in thesame way thatSO_BINDTODEVICE
is used, but with the index of anetwork interface instead of its name.
- socket.AF_CAN¶
- socket.PF_CAN¶
- SOL_CAN_*
- CAN_*
Many constants of these forms, documented in the Linux documentation, arealso defined in the socket module.
適用: Linux >= 2.6.25, NetBSD >= 8.
在 3.3 版被加入.
在 3.11 版的變更:NetBSD support was added.
在 3.13.3 (unreleased) 版的變更:Restored missing
CAN_RAW_ERR_FILTER
on Linux.
- socket.CAN_BCM¶
- CAN_BCM_*
CAN_BCM, in the CAN protocol family, is the broadcast manager (BCM) protocol.Broadcast manager constants, documented in the Linux documentation, are alsodefined in the socket module.
適用: Linux >= 2.6.25.
備註
The
CAN_BCM_CAN_FD_FRAME
flag is only available on Linux >= 4.8.在 3.4 版被加入.
- socket.CAN_RAW_FD_FRAMES¶
Enables CAN FD support in a CAN_RAW socket. This is disabled by default.This allows your application to send both CAN and CAN FD frames; however,you must accept both CAN and CAN FD frames when reading from the socket.
This constant is documented in the Linux documentation.
適用: Linux >= 3.6.
在 3.5 版被加入.
- socket.CAN_RAW_JOIN_FILTERS¶
Joins the applied CAN filters such that only CAN frames that match allgiven CAN filters are passed to user space.
This constant is documented in the Linux documentation.
適用: Linux >= 4.1.
在 3.9 版被加入.
- socket.CAN_ISOTP¶
CAN_ISOTP, in the CAN protocol family, is the ISO-TP (ISO 15765-2) protocol.ISO-TP constants, documented in the Linux documentation.
適用: Linux >= 2.6.25.
在 3.7 版被加入.
- socket.CAN_J1939¶
CAN_J1939, in the CAN protocol family, is the SAE J1939 protocol.J1939 constants, documented in the Linux documentation.
適用: Linux >= 5.4.
在 3.9 版被加入.
- socket.AF_DIVERT¶
- socket.PF_DIVERT¶
These two constants, documented in the FreeBSD divert(4) manual page, arealso defined in the socket module.
適用: FreeBSD >= 14.0.
在 3.12 版被加入.
- socket.AF_PACKET¶
- socket.PF_PACKET¶
- PACKET_*
Many constants of these forms, documented in the Linux documentation, arealso defined in the socket module.
適用: Linux >= 2.2.
- socket.ETH_P_ALL¶
ETH_P_ALL
can be used in thesocket
constructor asproto for theAF_PACKET
family in order tocapture every packet, regardless of protocol.For more information, see thepacket(7) manpage.
適用: Linux.
在 3.12 版被加入.
- socket.AF_RDS¶
- socket.PF_RDS¶
- socket.SOL_RDS¶
- RDS_*
Many constants of these forms, documented in the Linux documentation, arealso defined in the socket module.
適用: Linux >= 2.6.30.
在 3.3 版被加入.
- socket.SIO_RCVALL¶
- socket.SIO_KEEPALIVE_VALS¶
- socket.SIO_LOOPBACK_FAST_PATH¶
- RCVALL_*
Constants for Windows' WSAIoctl(). The constants are used as arguments to the
ioctl()
method of socket objects.在 3.6 版的變更:加入
SIO_LOOPBACK_FAST_PATH
。
- TIPC_*
TIPC related constants, matching the ones exported by the C socket API. Seethe TIPC documentation for more information.
- socket.AF_ALG¶
- socket.SOL_ALG¶
- ALG_*
Constants for Linux Kernel cryptography.
適用: Linux >= 2.6.38.
在 3.6 版被加入.
- socket.AF_VSOCK¶
- socket.IOCTL_VM_SOCKETS_GET_LOCAL_CID¶
- VMADDR*
- SO_VM*
Constants for Linux host/guest communication.
適用: Linux >= 4.8.
在 3.7 版被加入.
- socket.has_ipv6¶
This constant contains a boolean value which indicates if IPv6 is supported onthis platform.
- socket.BDADDR_ANY¶
- socket.BDADDR_LOCAL¶
These are string constants containing Bluetooth addresses with specialmeanings. For example,
BDADDR_ANY
can be used to indicateany 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_FILTER
is onlyavailable on Linux and FreeBSD.HCI_TIME_STAMP
andHCI_DATA_DIR
are only available on Linux.
- socket.AF_QIPCRTR¶
Constant for Qualcomm's IPC router protocol, used to communicate withservice providing remote processors.
適用: Linux >= 4.7.
- socket.SCM_CREDS2¶
- socket.LOCAL_CREDS¶
- socket.LOCAL_CREDS_PERSISTENT¶
LOCAL_CREDS and LOCAL_CREDS_PERSISTENT can be usedwith SOCK_DGRAM, SOCK_STREAM sockets, equivalent toLinux/DragonFlyBSD SO_PASSCRED, while LOCAL_CREDSsends the credentials at first read, LOCAL_CREDS_PERSISTENTsends for each read, SCM_CREDS2 must be then used forthe latter for the message type.
在 3.11 版被加入.
適用: FreeBSD.
- socket.SO_INCOMING_CPU¶
Constant to optimize CPU locality, to be used in conjunction with
SO_REUSEPORT
.在 3.11 版被加入.
適用: Linux >= 3.9
- socket.AF_HYPERV¶
- socket.HV_PROTOCOL_RAW¶
- socket.HVSOCKET_CONNECT_TIMEOUT¶
- socket.HVSOCKET_CONNECT_TIMEOUT_MAX¶
- socket.HVSOCKET_CONNECTED_SUSPEND¶
- socket.HVSOCKET_ADDRESS_FLAG_PASSTHRU¶
- socket.HV_GUID_ZERO¶
- socket.HV_GUID_WILDCARD¶
- socket.HV_GUID_BROADCAST¶
- socket.HV_GUID_CHILDREN¶
- socket.HV_GUID_LOOPBACK¶
- socket.HV_GUID_PARENT¶
Constants for Windows Hyper-V sockets for host/guest communications.
適用: Windows.
在 3.12 版被加入.
- socket.ETHERTYPE_ARP¶
- socket.ETHERTYPE_IP¶
- socket.ETHERTYPE_IPV6¶
- socket.ETHERTYPE_VLAN¶
IEEE 802.3 protocol number.constants.
適用: Linux, FreeBSD, macOS.
在 3.12 版被加入.
- socket.SHUT_RD¶
- socket.SHUT_WR¶
- socket.SHUT_RDWR¶
These constants are used by the
shutdown()
method of socket objects.適用: not WASI.
函式¶
建立 sockets¶
The following functions all createsocket objects.
- classsocket.socket(family=AF_INET,type=SOCK_STREAM,proto=0,fileno=None)¶
Create a new socket using the given address family, socket type and protocolnumber. The address family should be
AF_INET
(the default),AF_INET6
,AF_UNIX
,AF_CAN
,AF_PACKET
,orAF_RDS
. The socket type should beSOCK_STREAM
(thedefault),SOCK_DGRAM
,SOCK_RAW
or perhaps one of the otherSOCK_
constants. The protocol number is usually zero and may be omittedor in the case where the address family isAF_CAN
the protocolshould be one ofCAN_RAW
,CAN_BCM
,CAN_ISOTP
orCAN_J1939
.Iffileno is specified, the values forfamily,type, andproto areauto-detected from the specified file descriptor. Auto-detection can beoverruled by calling the function with explicitfamily,type, orprotoarguments. This only affects how Python represents e.g. the return valueof
socket.getpeername()
but not the actual OS resource. Unlikesocket.fromfd()
,fileno will return the same socket and not aduplicate. This may help close a detached socket usingsocket.close()
.The newly created socket isnon-inheritable.
引發一個附帶引數
self
、family
、type
、protocol
的稽核事件socket.__new__
。在 3.3 版的變更:The AF_CAN family was added.The AF_RDS family was added.
在 3.4 版的變更:新增 CAN_BCM 協定。
在 3.4 版的變更:The returned socket is now non-inheritable.
在 3.7 版的變更:新增 CAN_ISOTP 協定。
在 3.7 版的變更:When
SOCK_NONBLOCK
orSOCK_CLOEXEC
bit flags are applied totype they are cleared, andsocket.type
will not reflect them. They are still passedto the underlying systemsocket()
call. Therefore,sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM|socket.SOCK_NONBLOCK)
will still create a non-blocking socket on OSes that support
SOCK_NONBLOCK
, butsock.type
will be set tosocket.SOCK_STREAM
.在 3.9 版的變更:新增 CAN_J1939 協定。
在 3.10 版的變更:新增 IPPROTO_MPTCP 協定。
- socket.socketpair([family[,type[,proto]]])¶
Build a pair of connected socket objects using the given address family, sockettype, and protocol number. Address family, socket type, and protocol number areas for the
socket()
function above. The default family isAF_UNIX
if defined on the platform; otherwise, the default isAF_INET
.The newly created sockets arenon-inheritable.
在 3.2 版的變更:The returned socket objects now support the whole socket API, ratherthan a subset.
在 3.4 版的變更:The returned sockets are now non-inheritable.
在 3.5 版的變更:新增對 Windows 的支援。
- socket.create_connection(address,timeout=GLOBAL_DEFAULT,source_address=None,*,all_errors=False)¶
Connect to a TCP service listening on the internetaddress (a 2-tuple
(host,port)
), and return the socket object. This is a higher-levelfunction thansocket.connect()
: ifhost is a non-numeric hostname,it will try to resolve it for bothAF_INET
andAF_INET6
,and then try to connect to all possible addresses in turn until aconnection succeeds. This makes it easy to write clients that arecompatible to both IPv4 and IPv6.Passing the optionaltimeout parameter will set the timeout on thesocket instance before attempting to connect. If notimeout issupplied, the global default timeout setting returned by
getdefaulttimeout()
is used.If supplied,source_address must be a 2-tuple
(host,port)
for thesocket to bind to as its source address before connecting. If host or portare '' or 0 respectively the OS default behavior will be used.When a connection cannot be created, an exception is raised. By default,it is the exception from the last address in the list. Ifall_errorsis
True
, it is anExceptionGroup
containing the errors of allattempts.在 3.2 版的變更:新增source_address。
在 3.11 版的變更:新增all_errors。
- socket.create_server(address,*,family=AF_INET,backlog=None,reuse_port=False,dualstack_ipv6=False)¶
Convenience function which creates a TCP socket bound toaddress (a 2-tuple
(host,port)
) and returns the socket object.family should be either
AF_INET
orAF_INET6
.backlog is the queue size passed tosocket.listen()
; if not specified, a default reasonable value is chosen.reuse_port dictates whether to set theSO_REUSEPORT
socket option.Ifdualstack_ipv6 is true,family is
AF_INET6
and the platformsupports it the socket will be able to accept both IPv4 and IPv6 connections,else it will raiseValueError
. Most POSIX platforms and Windows aresupposed to support this functionality.When this functionality is enabled the address returned bysocket.getpeername()
when an IPv4 connection occurs will be an IPv6address represented as an IPv4-mapped IPv6 address.Ifdualstack_ipv6 is false it will explicitly disable this functionalityon platforms that enable it by default (e.g. Linux).This parameter can be used in conjunction withhas_dualstack_ipv6()
:importsocketaddr=("",8080)# all interfaces, port 8080ifsocket.has_dualstack_ipv6():s=socket.create_server(addr,family=socket.AF_INET6,dualstack_ipv6=True)else:s=socket.create_server(addr)
備註
On POSIX platforms the
SO_REUSEADDR
socket option is set in order toimmediately reuse previous sockets which were bound on the sameaddressand remained in TIME_WAIT state.在 3.8 版被加入.
- socket.has_dualstack_ipv6()¶
Return
True
if the platform supports creating a TCP socket which canhandle both IPv4 and IPv6 connections.在 3.8 版被加入.
- socket.fromfd(fd,family,type,proto=0)¶
Duplicate the file descriptorfd (an integer as returned by a file object's
fileno()
method) and build a socket object from the result. Addressfamily, socket type and protocol number are as for thesocket()
functionabove. 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 ona socket passed to a program as standard input or output (such as a serverstarted by the Unix inet daemon). The socket is assumed to be in blocking mode.The newly created socket isnon-inheritable.
在 3.4 版的變更:The returned socket is now non-inheritable.
- socket.fromshare(data)¶
Instantiate a socket from data obtained from the
socket.share()
method. The socket is assumed to be in blocking mode.適用: Windows.
在 3.3 版被加入.
- socket.SocketType¶
This is a Python type object that represents the socket object type. It is thesame as
type(socket(...))
.
其他函式¶
Thesocket
module also offers various network-related services:
- socket.close(fd)¶
Close a socket file descriptor. This is like
os.close()
, but forsockets. On some platforms (most noticeable Windows)os.close()
does not work for socket file descriptors.在 3.7 版被加入.
- socket.getaddrinfo(host,port,family=AF_UNSPEC,type=0,proto=0,flags=0)¶
This function wraps the C function
getaddrinfo
of the underlying system.Translate thehost/port argument into a sequence of 5-tuples that containall the necessary arguments for creating a socket connected to that service.host is a domain name, a string representation of an IPv4/v6 addressor
None
.port is a string service name such as'http'
, a numericport number orNone
. By passingNone
as the value ofhostandport, you can passNULL
to the underlying C API.Thefamily,type andproto arguments can be optionally specifiedin order to provide options and limit the list of addresses returned.Pass their default values (
AF_UNSPEC
, 0, and 0, respectively)to not limit the results. See the note below for details.Theflags argument can be one or several of the
AI_*
constants,and will influence how results are computed and returned.For example,AI_NUMERICHOST
will disable domain name resolutionand will raise an error ifhost is a domain name.The function returns a list of 5-tuples with the following structure:
(family,type,proto,canonname,sockaddr)
In these tuples,family,type,proto are all integers and aremeant to be passed to the
socket()
function.canonname will bea string representing the canonical name of thehost ifAI_CANONNAME
is part of theflags argument; elsecanonnamewill be empty.sockaddr is a tuple describing a socket address, whoseformat depends on the returnedfamily (a(address,port)
2-tuple forAF_INET
, a(address,port,flowinfo,scope_id)
4-tuple forAF_INET6
), and is meant to be passed to thesocket.connect()
method.備註
If you intend to use results from
getaddrinfo()
to create a socket(rather than, for example, retrievecanonname),consider limiting the results bytype (e.g.SOCK_STREAM
orSOCK_DGRAM
) and/orproto (e.g.IPPROTO_TCP
orIPPROTO_UDP
) that your application can handle.The behavior with default values offamily,type,protoandflags is system-specific.
Many systems (for example, most Linux configurations) will return a sortedlist of all matching addresses.These addresses should generally be tried in order until a connection succeeds(possibly tried in parallel, for example, using aHappy Eyeballs algorithm).In these cases, limiting thetype and/orproto can help eliminateunsuccessful or unusable connection attempts.
Some systems will, however, only return a single address.(For example, this was reported on Solaris and AIX configurations.)On these systems, limiting thetype and/orproto helps ensure thatthis address is usable.
引發一個附帶引數
host
、port
、family
、type
、protocol
的稽核事件socket.getaddrinfo
。The following example fetches address information for a hypothetical TCPconnection to
example.org
on port 80 (results may differ on yoursystem if IPv6 isn't enabled):>>>socket.getaddrinfo("example.org",80,proto=socket.IPPROTO_TCP)[(socket.AF_INET6, socket.SOCK_STREAM, 6, '', ('2606:2800:220:1:248:1893:25c8:1946', 80, 0, 0)), (socket.AF_INET, socket.SOCK_STREAM, 6, '', ('93.184.216.34', 80))]
在 3.2 版的變更:parameters can now be passed using keyword arguments.
在 3.7 版的變更:for IPv6 multicast addresses, string representing an address will notcontain
%scope_id
part.
- socket.getfqdn([name])¶
Return a fully qualified domain name forname. Ifname is omitted or empty,it is interpreted as the local host. To find the fully qualified name, thehostname returned by
gethostbyaddr()
is checked, followed by aliases for thehost, if available. The first name which includes a period is selected. Incase no fully qualified domain name is available andname was provided,it is returned unchanged. Ifname was empty or equal to'0.0.0.0'
,the hostname fromgethostname()
is returned.
- socket.gethostbyname(hostname)¶
Translate a host name to IPv4 address format. The IPv4 address is returned as astring, such as
'100.50.200.5'
. If the host name is an IPv4 address itselfit is returned unchanged. Seegethostbyname_ex()
for a more completeinterface.gethostbyname()
does not support IPv6 name resolution, andgetaddrinfo()
should be used instead for IPv4/v6 dual stack support.引發一個附帶引數
hostname
的稽核事件socket.gethostbyname
。適用: not WASI.
- socket.gethostbyname_ex(hostname)¶
Translate a host name to IPv4 address format, extended interface. Return a3-tuple
(hostname,aliaslist,ipaddrlist)
wherehostname is the host'sprimary host name,aliaslist is a (possiblyempty) list of alternative host names for the same address, andipaddrlist isa list of IPv4 addresses for the same interface on the same host (often but notalways a single address).gethostbyname_ex()
does not support IPv6 nameresolution, andgetaddrinfo()
should be used instead for IPv4/v6 dualstack support.引發一個附帶引數
hostname
的稽核事件socket.gethostbyname
。適用: not WASI.
- socket.gethostname()¶
Return a string containing the hostname of the machine where the Pythoninterpreter is currently executing.
引發一個不附帶引數的稽核事件
socket.gethostname
。Note:
gethostname()
doesn't always return the fully qualified domainname; usegetfqdn()
for that.適用: not WASI.
- socket.gethostbyaddr(ip_address)¶
Return a 3-tuple
(hostname,aliaslist,ipaddrlist)
wherehostname is theprimary host name responding to the givenip_address,aliaslist is a(possibly empty) list of alternative host names for the same address, andipaddrlist is a list of IPv4/v6 addresses for the same interface on the samehost (most likely containing only a single address). To find the fully qualifieddomain name, use the functiongetfqdn()
.gethostbyaddr()
supportsboth IPv4 and IPv6.引發一個附帶引數
ip_address
的稽核事件socket.gethostbyaddr
。適用: not WASI.
- socket.getnameinfo(sockaddr,flags)¶
Translate a socket addresssockaddr into a 2-tuple
(host,port)
. Dependingon the settings offlags, the result can contain a fully qualified domain nameor numeric address representation inhost. Similarly,port can contain astring port name or a numeric port number.For IPv6 addresses,
%scope_id
is appended to the host part ifsockaddrcontains meaningfulscope_id. Usually this happens for multicast addresses.For more information aboutflags you can consultgetnameinfo(3).
引發一個附帶引數
sockaddr
的稽核事件socket.getnameinfo
。適用: not WASI.
- socket.getprotobyname(protocolname)¶
Translate an internet protocol name (for example,
'icmp'
) to a constantsuitable 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 chosenautomatically if the protocol is omitted or zero.適用: not WASI.
- socket.getservbyname(servicename[,protocolname])¶
Translate an internet service name and protocol name to a port number for thatservice. The optional protocol name, if given, should be
'tcp'
or'udp'
, otherwise any protocol will match.引發一個附帶引數
sockaddr
、protocolname
的稽核事件socket.getservbyname
。適用: not WASI.
- socket.getservbyport(port[,protocolname])¶
Translate an internet port number and protocol name to a service name for thatservice. The optional protocol name, if given, should be
'tcp'
or'udp'
, otherwise any protocol will match.引發一個附帶引數
port
、protocolname
的稽核事件socket.getservbyport
。適用: not WASI.
- socket.ntohl(x)¶
Convert 32-bit positive integers from network to host byte order. On machineswhere 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 machineswhere the host byte order is the same as network byte order, this is a no-op;otherwise, it performs a 2-byte swap operation.
在 3.10 版的變更:Raises
OverflowError
ifx does not fit in a 16-bit unsignedinteger.
- socket.htonl(x)¶
Convert 32-bit positive integers from host to network byte order. On machineswhere 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 machineswhere the host byte order is the same as network byte order, this is a no-op;otherwise, it performs a 2-byte swap operation.
在 3.10 版的變更:Raises
OverflowError
ifx does not fit in a 16-bit unsignedinteger.
- 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 inlength. This is useful when conversing with a program that uses the standard Clibrary and needs objects of type
in_addr
, which is the C typefor the 32-bit packed binary this function returns.inet_aton()
also accepts strings with less than three dots; see theUnix manual pageinet(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 onthe underlying C implementation ofinet_aton()
.inet_aton()
does not support IPv6, andinet_pton()
should be usedinstead for IPv4/v6 dual stack support.
- socket.inet_ntoa(packed_ip)¶
Convert a 32-bit packed IPv4 address (abytes-like object fourbytes 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 thestandard C library and needs objects of type
in_addr
, whichis the C type for the 32-bit packed binary data this function takes as anargument.If the byte sequence passed to this function is not exactly 4 bytes inlength,
OSError
will be raised.inet_ntoa()
does notsupport IPv6, andinet_ntop()
should be used instead for IPv4/v6 dualstack support.在 3.5 版的變更:Writablebytes-like object is now accepted.
- socket.inet_pton(address_family,ip_string)¶
Convert an IP address from its family-specific string format to a packed,binary format.
inet_pton()
is useful when a library or network protocolcalls for an object of typein_addr
(similar toinet_aton()
) orin6_addr
.Supported values foraddress_family are currently
AF_INET
andAF_INET6
. If the IP address stringip_string is invalid,OSError
will be raised. Note that exactly what is valid depends onboth the value ofaddress_family and the underlying implementation ofinet_pton()
.適用: Unix, Windows.
在 3.4 版的變更:Windows support added
- socket.inet_ntop(address_family,packed_ip)¶
Convert a packed IP address (abytes-like object of some number ofbytes) to its standard, family-specific string representation (forexample,
'7.10.0.5'
or'5aef:2b::8'
).inet_ntop()
is useful when a library or network protocol returns anobject of typein_addr
(similar toinet_ntoa()
) orin6_addr
.Supported values foraddress_family are currently
AF_INET
andAF_INET6
. If the bytes objectpacked_ip is not the correctlength for the specified address family,ValueError
will be raised.OSError
is raised for errors from the call toinet_ntop()
.適用: Unix, Windows.
在 3.4 版的變更:Windows support added
在 3.5 版的變更:Writablebytes-like object is now accepted.
- socket.CMSG_LEN(length)¶
Return the total length, without trailing padding, of an ancillarydata item with associated data of the givenlength. This valuecan often be used as the buffer size for
recvmsg()
toreceive a single item of ancillary data, butRFC 3542 requiresportable applications to useCMSG_SPACE()
and thus includespace for padding, even when the item will be the last in thebuffer. RaisesOverflowError
iflength is outside thepermissible range of values.適用: Unix, not WASI.
Most Unix platforms.
在 3.3 版被加入.
- socket.CMSG_SPACE(length)¶
Return the buffer size needed for
recvmsg()
toreceive an ancillary data item with associated data of the givenlength, along with any trailing padding. The buffer space neededto receive multiple items is the sum of theCMSG_SPACE()
values for their associated data lengths. RaisesOverflowError
iflength is outside the permissible rangeof values.Note that some systems might support ancillary data withoutproviding this function. Also note that setting the buffer sizeusing the results of this function may not precisely limit theamount of ancillary data that can be received, since additionaldata may be able to fit into the padding area.
適用: Unix, not WASI.
most Unix platforms.
在 3.3 版被加入.
- socket.getdefaulttimeout()¶
Return the default timeout in seconds (float) for new socket objects. A valueof
None
indicates that new socket objects have no timeout. When the socketmodule is first imported, the default isNone
.
- socket.setdefaulttimeout(timeout)¶
Set the default timeout in seconds (float) for new socket objects. Whenthe socket module is first imported, the default is
None
. Seesettimeout()
for possible values and their respectivemeanings.
- socket.sethostname(name)¶
Set the machine's hostname toname. This will raise an
OSError
if you don't have enough rights.引發一個附帶引數
name
的稽核事件socket.sethostname
。適用: Unix, not Android.
在 3.3 版被加入.
- socket.if_nameindex()¶
Return a list of network interface information(index int, name string) tuples.
OSError
if the system call fails.適用: Unix, Windows, not WASI.
在 3.3 版被加入.
在 3.8 版的變更:增加對 Windows 的支援。
備註
On Windows network interfaces have different names in different contexts(all names are examples):
UUID:
{FB605B73-AAC2-49A6-9A2F-25416AEA0573}
name:
ethernet_32770
friendly name:
vEthernet(nat)
description:
Hyper-VVirtualEthernetAdapter
This function returns names of the second form from the list,
ethernet_32770
in this example case.
- socket.if_nametoindex(if_name)¶
Return a network interface index number corresponding to aninterface name.
OSError
if no interface with the given name exists.適用: Unix, Windows, not WASI.
在 3.3 版被加入.
在 3.8 版的變更:增加對 Windows 的支援。
也參考
"Interface name" is a name as documented in
if_nameindex()
.
- socket.if_indextoname(if_index)¶
Return a network interface name corresponding to aninterface index number.
OSError
if no interface with the given index exists.適用: Unix, Windows, not WASI.
在 3.3 版被加入.
在 3.8 版的變更:增加對 Windows 的支援。
也參考
"Interface name" is a name as documented in
if_nameindex()
.
Socket 物件¶
Socket objects have the following methods. Except formakefile()
, these correspond to Unix system calls applicableto sockets.
在 3.2 版的變更:Support for thecontext manager protocol was added. Exiting thecontext manager is equivalent to callingclose()
.
- socket.accept()¶
Accept a connection. The socket must be bound to an address and listening forconnections. The return value is a pair
(conn,address)
whereconn is anew socket object usable to send and receive data on the connection, andaddress is the address bound to the socket on the other end of the connection.The newly created socket isnon-inheritable.
在 3.4 版的變更:The socket is now non-inheritable.
在 3.5 版的變更:If the system call is interrupted and the signal handler does not raisean exception, the method now retries the system call instead of raisingan
InterruptedError
exception (seePEP 475 for the rationale).
- socket.bind(address)¶
Bind the socket toaddress. The socket must not already be bound. (The formatofaddress depends on the address family --- see above.)
引發一個附帶引數
self
、address
的稽核事件socket.bind
。適用: not WASI.
- socket.close()¶
Mark the socket closed. The underlying system resource (e.g. a filedescriptor) is also closed when all file objects from
makefile()
are closed. Once that happens, all future operations on the socketobject will fail. The remote end will receive no more data (afterqueued data is flushed).Sockets are automatically closed when they are garbage-collected, butit is recommended to
close()
them explicitly, or to use awith
statement around them.在 3.6 版的變更:
OSError
is now raised if an error occurs when the underlyingclose()
call is made.備註
close()
releases the resource associated with a connection butdoes not necessarily close the connection immediately. If you wantto close the connection in a timely fashion, callshutdown()
beforeclose()
.
- socket.connect(address)¶
Connect to a remote socket ataddress. (The format ofaddress depends on theaddress family --- see above.)
If the connection is interrupted by a signal, the method waits until theconnection completes, or raise a
TimeoutError
on timeout, if thesignal handler doesn't raise an exception and the socket is blocking or hasa timeout. For non-blocking sockets, the method raises anInterruptedError
exception if the connection is interrupted by asignal (or the exception raised by the signal handler).引發一個附帶引數
self
、address
的稽核事件socket.connect
。在 3.5 版的變更:The method now waits until the connection completes instead of raising an
InterruptedError
exception if the connection is interrupted by asignal, the signal handler doesn't raise an exception and the socket isblocking or has a timeout (see thePEP 475 for the rationale).適用: not WASI.
- socket.connect_ex(address)¶
Like
connect(address)
, but return an error indicator instead of raising anexception for errors returned by the C-levelconnect()
call (otherproblems, such as "host not found," can still raise exceptions). The errorindicator is0
if the operation succeeded, otherwise the value of theerrno
variable. This is useful to support, for example, asynchronousconnects.引發一個附帶引數
self
、address
的稽核事件socket.connect
。適用: not WASI.
- socket.detach()¶
Put the socket object into closed state without actually closing theunderlying file descriptor. The file descriptor is returned, and canbe reused for other purposes.
在 3.2 版被加入.
- socket.dup()¶
Duplicate the socket.
The newly created socket isnon-inheritable.
在 3.4 版的變更:The socket is now non-inheritable.
適用: not WASI.
- socket.fileno()¶
Return the socket's file descriptor (a small integer), or -1 on failure. Thisis useful with
select.select()
.Under Windows the small integer returned by this method cannot be used where afile descriptor can be used (such as
os.fdopen()
). Unix does not havethis limitation.
- socket.get_inheritable()¶
Get theinheritable flag of the socket's filedescriptor or socket's handle:
True
if the socket can be inherited inchild processes,False
if it cannot.在 3.4 版被加入.
- socket.getpeername()¶
Return the remote address to which the socket is connected. This is useful tofind out the port number of a remote IPv4/v6 socket, for instance. (The formatof the address returned depends on the address family --- see above.) On somesystems this function is not supported.
- socket.getsockname()¶
Return the socket's own address. This is useful to find out the port number ofan IPv4/v6 socket, for instance. (The format of the address returned depends onthe address family --- see above.)
- socket.getsockopt(level,optname[,buflen])¶
Return the value of the given socket option (see the Unix man pagegetsockopt(2)). The needed symbolic constants (SO_* etc.)are defined in this module. Ifbuflen is absent, an integer option is assumedand its integer value is returned by the function. Ifbuflen is present, itspecifies the maximum length of the buffer used to receive the option in, andthis buffer is returned as a bytes object. It is up to the caller to decode thecontents of the buffer (see the optional built-in module
struct
for a wayto decode C structures encoded as byte strings).適用: not WASI.
- socket.getblocking()¶
Return
True
if socket is in blocking mode,False
if innon-blocking.這等同於檢查
socket.gettimeout()!=0
。在 3.7 版被加入.
- socket.gettimeout()¶
Return the timeout in seconds (float) associated with socket operations,or
None
if no timeout is set. This reflects the last call tosetblocking()
orsettimeout()
.
- socket.ioctl(control,option)¶
- 平台:
Windows
The
ioctl()
method is a limited interface to the WSAIoctl systeminterface. Please refer to theWin32 documentation for moreinformation.On other platforms, the generic
fcntl.fcntl()
andfcntl.ioctl()
functions may be used; they accept a socket object as their first argument.Currently only the following control codes are supported:
SIO_RCVALL
,SIO_KEEPALIVE_VALS
, andSIO_LOOPBACK_FAST_PATH
.在 3.6 版的變更:加入
SIO_LOOPBACK_FAST_PATH
。
- socket.listen([backlog])¶
Enable a server to accept connections. Ifbacklog is specified, it mustbe at least 0 (if it is lower, it is set to 0); it specifies the number ofunaccepted connections that the system will allow before refusing newconnections. If not specified, a default reasonable value is chosen.
適用: not WASI.
在 3.5 版的變更:Thebacklog parameter is now optional.
- socket.makefile(mode='r',buffering=None,*,encoding=None,errors=None,newline=None)¶
Return afile object associated with the socket. The exact returnedtype depends on the arguments given to
makefile()
. These arguments areinterpreted the same way as by the built-inopen()
function, exceptthe only supportedmode values are'r'
(default),'w'
,'b'
, ora combination of those.The socket must be in blocking mode; it can have a timeout, but the fileobject's internal buffer may end up in an inconsistent state if a timeoutoccurs.
Closing the file object returned by
makefile()
won't close theoriginal socket unless all other file objects have been closed andsocket.close()
has been called on the socket object.備註
On Windows, the file-like object created by
makefile()
cannot beused where a file object with a file descriptor is expected, such as thestream arguments ofsubprocess.Popen()
.
- socket.recv(bufsize[,flags])¶
Receive data from the socket. The return value is a bytes object representing thedata received. The maximum amount of data to be received at once is specifiedbybufsize. A returned empty bytes object indicates that the client has disconnected.See the Unix manual pagerecv(2) for the meaning of the optional argumentflags; it defaults to zero.
在 3.5 版的變更:If the system call is interrupted and the signal handler does not raisean exception, the method now retries the system call instead of raisingan
InterruptedError
exception (seePEP 475 for the rationale).
- socket.recvfrom(bufsize[,flags])¶
Receive data from the socket. The return value is a pair
(bytes,address)
wherebytes is a bytes object representing the data received andaddress is theaddress of the socket sending the data. See the Unix manual pagerecv(2) for the meaning of the optional argumentflags; it defaultsto zero. (The format ofaddress depends on the address family --- see above.)在 3.5 版的變更:If the system call is interrupted and the signal handler does not raisean exception, the method now retries the system call instead of raisingan
InterruptedError
exception (seePEP 475 for the rationale).在 3.7 版的變更:For multicast IPv6 address, first item ofaddress does not contain
%scope_id
part anymore. In order to get full IPv6 address usegetnameinfo()
.
- socket.recvmsg(bufsize[,ancbufsize[,flags]])¶
Receive normal data (up tobufsize bytes) and ancillary data fromthe socket. Theancbufsize argument sets the size in bytes ofthe internal buffer used to receive the ancillary data; it defaultsto 0, meaning that no ancillary data will be received. Appropriatebuffer sizes for ancillary data can be calculated using
CMSG_SPACE()
orCMSG_LEN()
, and items which do not fitinto the buffer might be truncated or discarded. Theflagsargument defaults to 0 and has the same meaning as forrecv()
.The return value is a 4-tuple:
(data,ancdata,msg_flags,address)
. Thedata item is abytes
object holding thenon-ancillary data received. Theancdata item is a list of zeroor more tuples(cmsg_level,cmsg_type,cmsg_data)
representingthe ancillary data (control messages) received:cmsg_level andcmsg_type are integers specifying the protocol level andprotocol-specific type respectively, andcmsg_data is abytes
object holding the associated data. Themsg_flagsitem is the bitwise OR of various flags indicating conditions onthe received message; see your system documentation for details.If the receiving socket is unconnected,address is the address ofthe sending socket, if available; otherwise, its value isunspecified.On some systems,
sendmsg()
andrecvmsg()
can be used topass file descriptors between processes over anAF_UNIX
socket. When this facility is used (it is often restricted toSOCK_STREAM
sockets),recvmsg()
will return, in itsancillary data, items of the form(socket.SOL_SOCKET,socket.SCM_RIGHTS,fds)
, wherefds is abytes
objectrepresenting the new file descriptors as a binary array of thenative Cint type. Ifrecvmsg()
raises anexception after the system call returns, it will first attempt toclose any file descriptors received via this mechanism.Some systems do not indicate the truncated length of ancillary dataitems which have been only partially received. If an item appearsto extend beyond the end of the buffer,
recvmsg()
will issueaRuntimeWarning
, and will return the part of it which isinside the buffer provided it has not been truncated before thestart of its associated data.On systems which support the
SCM_RIGHTS
mechanism, thefollowing function will receive up tomaxfds file descriptors,returning the message data and a list containing the descriptors(while ignoring unexpected conditions such as unrelated controlmessages being received). See alsosendmsg()
.importsocket,arraydefrecv_fds(sock,msglen,maxfds):fds=array.array("i")# Array of intsmsg,ancdata,flags,addr=sock.recvmsg(msglen,socket.CMSG_LEN(maxfds*fds.itemsize))forcmsg_level,cmsg_type,cmsg_datainancdata:ifcmsg_level==socket.SOL_SOCKETandcmsg_type==socket.SCM_RIGHTS:# Append data, ignoring any truncated integers at the end.fds.frombytes(cmsg_data[:len(cmsg_data)-(len(cmsg_data)%fds.itemsize)])returnmsg,list(fds)
適用: Unix.
Most Unix platforms.
在 3.3 版被加入.
在 3.5 版的變更:If the system call is interrupted and the signal handler does not raisean exception, the method now retries the system call instead of raisingan
InterruptedError
exception (seePEP 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 aseries of buffers instead of returning a new bytes object. Thebuffers argument must be an iterable of objects that exportwritable buffers (e.g.bytearray
objects); these will befilled with successive chunks of the non-ancillary data until ithas all been written or there are no more buffers. The operatingsystem may set a limit (sysconf()
valueSC_IOV_MAX
)on the number of buffers that can be used. Theancbufsize andflags arguments have the same meaning as forrecvmsg()
.The return value is a 4-tuple:
(nbytes,ancdata,msg_flags,address)
, wherenbytes is the total number of bytes ofnon-ancillary data written into the buffers, andancdata,msg_flags andaddress are the same as forrecvmsg()
.範例:
>>>importsocket>>>s1,s2=socket.socketpair()>>>b1=bytearray(b'----')>>>b2=bytearray(b'0123456789')>>>b3=bytearray(b'--------------')>>>s1.send(b'Mary had a little lamb')22>>>s2.recvmsg_into([b1,memoryview(b2)[2:9],b3])(22, [], 0, None)>>>[b1,b2,b3][bytearray(b'Mary'), bytearray(b'01 had a 9'), bytearray(b'little lamb---')]
適用: Unix.
Most Unix platforms.
在 3.3 版被加入.
- socket.recvfrom_into(buffer[,nbytes[,flags]])¶
Receive data from the socket, writing it intobuffer instead of creating anew bytestring. The return value is a pair
(nbytes,address)
wherenbytes isthe number of bytes received andaddress is the address of the socket sendingthe data. See the Unix manual pagerecv(2) for the meaning of theoptional argumentflags; it defaults to zero. (The format ofaddressdepends on the address family --- see above.)
- socket.recv_into(buffer[,nbytes[,flags]])¶
Receive up tonbytes bytes from the socket, storing the data into a bufferrather than creating a new bytestring. Ifnbytes is not specified (or 0),receive up to the size available in the given buffer. Returns the number ofbytes received. See the Unix manual pagerecv(2) for the meaningof the optional argumentflags; it defaults to zero.
- socket.send(bytes[,flags])¶
Send data to the socket. The socket must be connected to a remote socket. Theoptionalflags argument has the same meaning as for
recv()
above.Returns the number of bytes sent. Applications are responsible for checking thatall data has been sent; if only some of the data was transmitted, theapplication needs to attempt delivery of the remaining data. For furtherinformation on this topic, consult theSocket 程式設計指南.在 3.5 版的變更:If the system call is interrupted and the signal handler does not raisean exception, the method now retries the system call instead of raisingan
InterruptedError
exception (seePEP 475 for the rationale).
- socket.sendall(bytes[,flags])¶
Send data to the socket. The socket must be connected to a remote socket. Theoptionalflags argument has the same meaning as for
recv()
above.Unlikesend()
, this method continues to send data frombytes untileither all data has been sent or an error occurs.None
is returned onsuccess. On error, an exception is raised, and there is no way to determine howmuch data, if any, was successfully sent.在 3.5 版的變更:The socket timeout is no longer reset each time data is sent successfully.The socket timeout is now the maximum total duration to send all data.
在 3.5 版的變更:If the system call is interrupted and the signal handler does not raisean exception, the method now retries the system call instead of raisingan
InterruptedError
exception (seePEP 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 byaddress. The optionalflagsargument has the same meaning as for
recv()
above. Return the number ofbytes sent. (The format ofaddress depends on the address family --- seeabove.)引發一個附帶引數
self
、address
的稽核事件socket.sendto
。在 3.5 版的變更:If the system call is interrupted and the signal handler does not raisean exception, the method now retries the system call instead of raisingan
InterruptedError
exception (seePEP 475 for the rationale).
- socket.sendmsg(buffers[,ancdata[,flags[,address]]])¶
Send normal and ancillary data to the socket, gathering thenon-ancillary data from a series of buffers and concatenating itinto a single message. Thebuffers argument specifies thenon-ancillary data as an iterable ofbytes-like objects(e.g.
bytes
objects); the operating system may set a limit(sysconf()
valueSC_IOV_MAX
) on the number of buffersthat can be used. Theancdata argument specifies the ancillarydata (control messages) as an iterable of zero or more tuples(cmsg_level,cmsg_type,cmsg_data)
, wherecmsg_level andcmsg_type are integers specifying the protocol level andprotocol-specific type respectively, andcmsg_data is abytes-like object holding the associated data. Note thatsome systems (in particular, systems withoutCMSG_SPACE()
)might support sending only one control message per call. Theflags argument defaults to 0 and has the same meaning as forsend()
. Ifaddress is supplied and notNone
, it sets adestination address for the message. The return value is thenumber of bytes of non-ancillary data sent.The following function sends the list of file descriptorsfdsover an
AF_UNIX
socket, on systems which support theSCM_RIGHTS
mechanism. See alsorecvmsg()
.importsocket,arraydefsend_fds(sock,msg,fds):returnsock.sendmsg([msg],[(socket.SOL_SOCKET,socket.SCM_RIGHTS,array.array("i",fds))])
適用: Unix, not WASI.
Most Unix platforms.
引發一個附帶引數
self
、address
的稽核事件socket.sendmsg
。在 3.3 版被加入.
在 3.5 版的變更:If the system call is interrupted and the signal handler does not raisean exception, the method now retries the system call instead of raisingan
InterruptedError
exception (seePEP 475 for the rationale).
- socket.sendmsg_afalg([msg,]*,op[,iv[,assoclen[,flags]]])¶
Specialized version of
sendmsg()
forAF_ALG
socket.Set mode, IV, AEAD associated data length and flags forAF_ALG
socket.適用: Linux >= 2.6.38.
在 3.6 版被加入.
- 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. Ifos.sendfile
is not available (e.g. Windows) orfile is not aregular filesend()
will be used instead.offset tells from where tostart reading the file. If specified,count is the total number of bytesto transmit as opposed to sending the file until EOF is reached. Fileposition is updated on return or also in case of error in which casefile.tell()
can be used to figure out the number ofbytes which were sent. The socket must be ofSOCK_STREAM
type.Non-blocking sockets are not supported.在 3.5 版被加入.
- socket.set_inheritable(inheritable)¶
Set theinheritable flag of the socket's filedescriptor or socket's handle.
在 3.4 版被加入.
- socket.setblocking(flag)¶
Set blocking or non-blocking mode of the socket: ifflag is false, thesocket is set to non-blocking, else to blocking mode.
This method is a shorthand for certain
settimeout()
calls:sock.setblocking(True)
等價於sock.settimeout(None)
sock.setblocking(False)
等價於sock.settimeout(0.0)
在 3.7 版的變更:The method no longer applies
SOCK_NONBLOCK
flag onsocket.type
.
- socket.settimeout(value)¶
Set a timeout on blocking socket operations. Thevalue argument can be anonnegative floating-point number expressing seconds, or
None
.If a non-zero value is given, subsequent socket operations will raise atimeout
exception if the timeout periodvalue has elapsed beforethe operation has completed. If zero is given, the socket is put innon-blocking mode. IfNone
is given, the socket is put in blocking mode.For further information, please consult thenotes on socket timeouts.
在 3.7 版的變更:The method no longer toggles
SOCK_NONBLOCK
flag onsocket.type
.
- socket.setsockopt(level,optname,value:buffer)
- socket.setsockopt(level,optname,None,optlen:int)
Set the value of the given socket option (see the Unix manual pagesetsockopt(2)). The needed symbolic constants are defined in thismodule (SO_* etc. <socket-unix-constants>). The value can be an integer,
None
or abytes-like object representing a buffer. In the latercase it is up to the caller to ensure that the bytestring contains theproper bits (see the optional built-in modulestruct
for a way toencode C structures as bytestrings). Whenvalue is set toNone
,optlen argument is required. It's equivalent to callsetsockopt()
Cfunction withoptval=NULL
andoptlen=optlen
.在 3.5 版的變更:Writablebytes-like object is now accepted.
在 3.6 版的變更:setsockopt(level, optname, None, optlen: int) form added.
適用: not WASI.
- socket.shutdown(how)¶
Shut down one or both halves of the connection. Ifhow is
SHUT_RD
,further receives are disallowed. Ifhow isSHUT_WR
, further sendsare disallowed. Ifhow isSHUT_RDWR
, further sends and receives aredisallowed.適用: not WASI.
- socket.share(process_id)¶
Duplicate a socket and prepare it for sharing with a target process. Thetarget process must be provided withprocess_id. The resulting bytes objectcan then be passed to the target process using some form of interprocesscommunication and the socket can be recreated there using
fromshare()
.Once this method has been called, it is safe to close the socket sincethe operating system has already duplicated it for the target process.適用: Windows.
在 3.3 版被加入.
Note that there are no methodsread()
orwrite()
; userecv()
andsend()
withoutflags argument instead.
Socket objects also have these (read-only) attributes that correspond to thevalues given to thesocket
constructor.
- socket.family¶
The socket family.
- socket.type¶
The socket type.
- socket.proto¶
The socket protocol.
Notes on socket timeouts¶
A socket object can be in one of three modes: blocking, non-blocking, ortimeout. Sockets are by default always created in blocking mode, but thiscan be changed by callingsetdefaulttimeout()
.
Inblocking mode, operations block until complete or the system returnsan error (such as connection timed out).
Innon-blocking mode, operations fail (with an error that is unfortunatelysystem-dependent) if they cannot be completed immediately: functions from the
select
module can be used to know when and whether a socket is availablefor reading or writing.Intimeout mode, operations fail if they cannot be completed within thetimeout specified for the socket (they raise a
timeout
exception)or if the system returns an error.
備註
At the operating system level, sockets intimeout mode are internally setin non-blocking mode. Also, the blocking and timeout modes are shared betweenfile descriptors and socket objects that refer to the same network endpoint.This implementation detail can have visible consequences if e.g. you decideto use thefileno()
of a socket.
Timeouts and theconnect
method¶
Theconnect()
operation is also subject to the timeoutsetting, and in general it is recommended to callsettimeout()
before callingconnect()
or pass a timeout parameter tocreate_connection()
. However, the system network stack may alsoreturn a connection timeout error of its own regardless of any Python sockettimeout setting.
Timeouts and theaccept
method¶
Ifgetdefaulttimeout()
is notNone
, sockets returned bytheaccept()
method inherit that timeout. Otherwise, thebehaviour depends on settings of the listening socket:
if the listening socket is inblocking mode or intimeout mode,the socket returned by
accept()
is inblocking mode;if the listening socket is innon-blocking mode, whether the socketreturned by
accept()
is in blocking or non-blocking modeis operating system-dependent. If you want to ensure cross-platformbehaviour, it is recommended you manually override this setting.
範例¶
Here are four minimal example programs using the TCP/IP protocol: a server thatechoes all data that it receives back (servicing only one client), and a clientusing it. Note that a server must perform the sequencesocket()
,bind()
,listen()
,accept()
(possiblyrepeating theaccept()
to service more than one client), while aclient only needs the sequencesocket()
,connect()
. Alsonote that the server does notsendall()
/recv()
onthe socket it is listening on but on the new socket returned byaccept()
.
前兩個範例只支援 IPv4:
# Echo server programimportsocketHOST=''# Symbolic name meaning all available interfacesPORT=50007# Arbitrary non-privileged portwithsocket.socket(socket.AF_INET,socket.SOCK_STREAM)ass:s.bind((HOST,PORT))s.listen(1)conn,addr=s.accept()withconn:print('Connected by',addr)whileTrue:data=conn.recv(1024)ifnotdata:breakconn.sendall(data)
# Echo client programimportsocketHOST='daring.cwi.nl'# The remote hostPORT=50007# The same port as used by the serverwithsocket.socket(socket.AF_INET,socket.SOCK_STREAM)ass: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 andIPv6. The server side will listen to the first address family available (itshould listen to both instead). On most of IPv6-ready systems, IPv6 will takeprecedence and the server may not accept IPv4 traffic. The client side will tryto connect to all the addresses returned as a result of the name resolution, andsends traffic to the first one connected successfully.
# Echo server programimportsocketimportsysHOST=None# Symbolic name meaning all available interfacesPORT=50007# Arbitrary non-privileged ports=Noneforresinsocket.getaddrinfo(HOST,PORT,socket.AF_UNSPEC,socket.SOCK_STREAM,0,socket.AI_PASSIVE):af,socktype,proto,canonname,sa=restry:s=socket.socket(af,socktype,proto)exceptOSErrorasmsg:s=Nonecontinuetry:s.bind(sa)s.listen(1)exceptOSErrorasmsg:s.close()s=NonecontinuebreakifsisNone:print('could not open socket')sys.exit(1)conn,addr=s.accept()withconn:print('Connected by',addr)whileTrue:data=conn.recv(1024)ifnotdata:breakconn.send(data)
# Echo client programimportsocketimportsysHOST='daring.cwi.nl'# The remote hostPORT=50007# The same port as used by the servers=Noneforresinsocket.getaddrinfo(HOST,PORT,socket.AF_UNSPEC,socket.SOCK_STREAM):af,socktype,proto,canonname,sa=restry:s=socket.socket(af,socktype,proto)exceptOSErrorasmsg:s=Nonecontinuetry:s.connect(sa)exceptOSErrorasmsg:s.close()s=NonecontinuebreakifsisNone:print('could not open socket')sys.exit(1)withs: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 rawsockets on Windows. The example requires administrator privileges to modifythe interface:
importsocket# the public network interfaceHOST=socket.gethostbyname(socket.gethostname())# create a raw socket and bind it to the public interfaces=socket.socket(socket.AF_INET,socket.SOCK_RAW,socket.IPPROTO_IP)s.bind((HOST,0))# Include IP headerss.setsockopt(socket.IPPROTO_IP,socket.IP_HDRINCL,1)# receive all packetss.ioctl(socket.SIO_RCVALL,socket.RCVALL_ON)# receive a packetprint(s.recvfrom(65565))# disabled promiscuous modes.ioctl(socket.SIO_RCVALL,socket.RCVALL_OFF)
The next example shows how to use the socket interface to communicate to a CANnetwork using the raw socket protocol. To use CAN with the broadcastmanager 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, youcan use thesocket.send()
andsocket.recv()
operations (andtheir counterparts) on the socket object as usual.
This last example might require special privileges:
importsocketimportstruct# CAN frame packing/unpacking (see 'struct can_frame' in <linux/can.h>)can_frame_fmt="=IB3x8s"can_frame_size=struct.calcsize(can_frame_fmt)defbuild_can_frame(can_id,data):can_dlc=len(data)data=data.ljust(8,b'\x00')returnstruct.pack(can_frame_fmt,can_id,can_dlc,data)defdissect_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' interfaces=socket.socket(socket.AF_CAN,socket.SOCK_RAW,socket.CAN_RAW)s.bind(('vcan0',))whileTrue: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)exceptOSError:print('Error sending CAN frame')try:s.send(build_can_frame(0x01,b'\x01\x02\x03'))exceptOSError:print('Error sending CAN frame')
Running an example several times with too small delay between executions, couldlead to this error:
OSError:[Errno98]Addressalreadyinuse
This is because the previous execution has left the socket in aTIME_WAIT
state, and can't be immediately reused.
There is asocket
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))
theSO_REUSEADDR
flag tells the kernel to reuse a local socket inTIME_WAIT
state, without waiting for its natural timeout to expire.
也參考
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 etal,
both in the UNIX Programmer's Manual, Supplementary Documents 1 (sectionsPS1:7 and PS1:8). The platform-specific reference material for the varioussocket-related system calls are also a valuable source of information on thedetails of socket semantics. For Unix, refer to the manual pages; for Windows,see the WinSock (or Winsock 2) specification. For IPv6-ready APIs, readers maywant to refer toRFC 3493 titled Basic Socket Interface Extensions for IPv6.