socket — 低階網路介面

原始碼:Lib/socket.py


這個模組提供了操作 BSD socket 的介面。這在所有現代 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 families are supported by this module.

The address format required by a particular socket object is automatically selected based on the address family specified when the socket object was created. Socket addresses are represented as follows:

  • The address of an AF_UNIX socket bound to a file system node is represented as a string, using the file system encoding and the 'surrogateescape' error handler (see PEP 383). An address in Linux's abstract namespace is returned as a bytes-like object with an initial null byte; note that sockets in this namespace can communicate with normal file system sockets, so programs intended to run on Linux may need to deal with both types of address. A string or bytes-like object can be used for either type of address when passing it as an argument.

    在 3.3 版的變更: Previously, AF_UNIX socket paths were assumed to use UTF-8 encoding.

    在 3.5 版的變更: Writable bytes-like object is now accepted.

  • A pair (host, port) is used for the AF_INET address family, where host is a string representing either a hostname in internet domain notation like 'daring.cwi.nl' or an IPv4 address like '100.50.200.5', and port is an integer.