在套接字编程中AF_INET和PF_INET的区别是什么?
我混淆了在socket()和bind()中使用AF_INET和PF_INET。
另外,如何给ip地址在sin_addr字段?
在套接字编程中AF_INET和PF_INET的区别是什么?
我混淆了在socket()和bind()中使用AF_INET和PF_INET。
另外,如何给ip地址在sin_addr字段?
当前回答
我在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指的是来自互联网的地址,特别是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不相同的真实情况。