查看有关套接字编程的示例,我们可以看到有些人使用AF_INET
,而其他人使用PF_INET
。此外,有时 both of them are used at the same example 。问题是:它们之间有什么区别吗?我们应该使用哪一个?
如果你能回答这个问题,另一个问题是……为什么会有这两个相似(但相等)的常量?
到目前为止我发现了什么:
socket
手册页
在 (Unix) 套接字编程中,我们有 socket()
函数,它接收以下参数:
int socket(int domain, int type, int protocol);
手册页说:
The
domain
argument specifies a communication domain; this selects the protocol family which will be used for communication. These families are defined in <sys/socket.h>.
并且手册页引用了 AF_INET
以及 domain
参数的其他一些 AF_
常量。此外,在同一手册页的 NOTES
部分,我们可以阅读:
The manifest constants used under 4.x BSD for protocol families are PF_UNIX, PF_INET, etc., while AF_UNIX etc. are used for address families. However, already the BSD man page promises: "The protocol family generally is the same as the address family", and subsequent standards use AF_* everywhere.
C 头文件
sys/socket.h
实际上并没有定义这些常量,而是包含 bits/socket.h
。该文件定义了大约 38 个 AF_
常量和 38 个 PF_
常量,如下所示:
#define PF_INET 2 /* IP protocol family. */
#define AF_INET PF_INET
Python
Python socket module 与 C API 非常相似。但是,有许多 AF_
常量,但只有一个 PF_
常量(PF_PACKET)。因此,在 Python 中我们别无选择,只能使用 AF_INET
。
我认为只包含 AF_
常量的决定遵循了指导原则之一:“应该有一种——最好只有一种——明显的方式来做到这一点。” (The Zen of Python)
其他信息
This forum post 链接到 this old message ,其中包含一些历史信息。
最佳答案
我认为 Wikipedia notes on this总结的很好:
The original design concept of the socket interface distinguished between protocol types (families) and the specific address types that each may use. It was envisioned that a protocol family may have several address types. Address types were defined by additional symbolic constants, using the prefix
AF_
instead ofPF_
. TheAF_
-identifiers are intended for all data structures that specifically deal with the address type and not the protocol family. However, this concept of separation of protocol and address type has not found implementation support and theAF_
-constants were simply defined by the corresponding protocol identifier, rendering the distinction betweenAF_
versusPF_
constants a technical argument of no significant practical consequence. Indeed, much confusion exists in the proper usage of both forms.
即使今天有人想出了一个与众不同的理由,他们也必须想出新的标识符,否则很多东西会被破坏......
关于python - AF_INET 和 PF_INET 常量有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2549461/