在套接字编程中AF_INET和PF_INET的区别是什么?

我混淆了在socket()和bind()中使用AF_INET和PF_INET。

另外,如何给ip地址在sin_addr字段?


地址族 协议族

意思是,AF_INET指的是来自互联网的地址,特别是IP地址。PF_INET指的是协议中的任何东西,通常是套接字/端口。

考虑阅读socket(2)和bind(2)的手册页。对于sin_addr字段,只需执行如下操作来设置它:

struct sockaddr_in addr;
inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr); 

Beej著名的网络编程指南给出了一个很好的解释:

In some documentation, you'll see mention of a mystical "PF_INET". This is a weird etherial beast that is rarely seen in nature, but I might as well clarify it a bit here. Once a long time ago, it was thought that maybe a address family (what the "AF" in "AF_INET" stands for) might support several protocols that were referenced by their protocol family (what the "PF" in "PF_INET" stands for). That didn't happen. Oh well. So the correct thing to do is to use AF_INET in your struct sockaddr_in and PF_INET in your call to socket(). But practically speaking, you can use AF_INET everywhere. And, since that's what W. Richard Stevens does in his book, that's what I'll do here.


我在Linux内核源代码中发现PF_INET和AF_INET是相同的。 以下代码来自linux内核3.2.21树的include/linux/socket.h文件,第204行。

/* Protocol families, same as address families. */
...
#define PF_INET     AF_INET

事实上,AF_和PF_是一样的。维基百科上有一些词可以帮你理清思路

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 of PF_. The AF_-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 the AF_-constants were simply defined by the corresponding protocol identifier, rendering the distinction between AF_ versus PF_ constants a technical argument of no significant practical consequence. Indeed, much confusion exists in the proper usage of both forms.


在某些情况下,这很重要。

如果你在Cygwin中将AF_INET传递给socket(),你的套接字可能会被随机重置,也可能不会。传递PF_INET确保连接正常工作。

Cygwin对套接字编程来说是一个巨大的混乱,但它是AF_INET和PF_INET不相同的真实情况。


AF_INET =地址格式,Internet = IP地址

PF_INET =数据包格式,Internet = IP, TCP/IP或UDP/IP

AF_INET是用于您正在创建的套接字的地址族(在本例中是Internet协议地址)。例如,Linux内核支持29个其他地址族,如UNIX套接字和IPX,还支持与IRDA和蓝牙(AF_IRDA和AF_BLUETOOTH,但在如此低的级别上使用它们是值得怀疑的)通信。

在大多数情况下,在网络上使用AF_INET进行套接字编程是最安全的选择。

意思是,AF_INET指的是来自互联网的地址,特别是IP地址。

PF_INET指的是协议中的任何东西,通常是套接字/端口。


检查头文件解决了这个问题。 可以检查系统编译器。

对于我的系统,AF_INET == PF_INET

AF =地址族,PF =协议族

协议族,与地址族相同。