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

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

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


当前回答

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

对于我的系统,AF_INET == PF_INET

AF =地址族,PF =协议族

协议族,与地址族相同。

其他回答

地址族 协议族

意思是,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.

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

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

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

我在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_INET == PF_INET

AF =地址族,PF =协议族

协议族,与地址族相同。