IPPROTO_IP与IPPROTO_TCP / IPPROTO_UDP [英] IPPROTO_IP vs IPPROTO_TCP/IPPROTO_UDP
问题描述
我在查找有关 socket
的第三个参数的这些设置之间区别的文档时遇到了一些问题。我知道TCP和UDP及其差异,以及IP是堆栈上的一层(向下?)...我的UDP代码似乎工作相同,无论我将其设置为 IPPROTO_IP
或 IPPROTO_UDP
。
I'm having some trouble finding documentation on what the distinction between these settings for the third argument to socket
is. I know about TCP and UDP and their differences and also that IP is one layer up (down?) on the stack... My UDP code seems to work the same whether I set it to IPPROTO_IP
or IPPROTO_UDP
.
推荐答案
Linux上 socket()
的文档分为各种联机帮助页包括 ip(7)
,指定你必须使用 0
或 IPPROTO_UDP
用于UDP, 0
或 IPPROTO_TCP
用于TCP。当您使用 0
(恰好是 IPPROTO_IP
的值时,UDP用于 SOCK_DGRAM
和TCP用于 SOCK_STREAM
。
Documentation for socket()
on Linux is split between various manpages including ip(7)
that specifies that you have to use 0
or IPPROTO_UDP
for UDP and 0
or IPPROTO_TCP
for TCP. When you use 0
, which happens to be the value of IPPROTO_IP
, UDP is used for SOCK_DGRAM
and TCP is used for SOCK_STREAM
.
在我看来,干净的方式是创建UDP或TCP IPv4套接字对象如下:
In my opinion the clean way to create a UDP or a TCP IPv4 socket object is as follows:
int sock_udp = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
int sock_tcp = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
原因是显性通常比隐式更好。在这种特殊情况下,使用 0
或更糟 IPPROTO_IP
第三个参数不会获得任何收益。
The reason is that it is generally better to be explicit than implicit. In this specific case using 0
or worse IPPROTO_IP
for the third argument doesn't gain you anything.
还可以设想使用可以同时执行流和数据报的协议,例如 sctp 。通过始终指定 socktype 和协议,您可以避免任何歧义。
Also imagine using a protocol that can do both streams and datagrams like sctp. By always specifying both socktype and protocol you are safe from any ambiguity.
这篇关于IPPROTO_IP与IPPROTO_TCP / IPPROTO_UDP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!