ip dontfrag linux,c – 如何在套接字上设置do not fragment(DF)标志?

这篇博客讨论了如何在Unix环境中使用setsockopt()函数设置UDP数据包的不分段标志,包括IP_DONTFRAG和IP_MTU_DISCOVER选项。在Linux中,可能需要使用IP_PMTUDISC_DO来启用Path MTU Discovery,并设置不分段标志。同时,提到了sysctl可以用来设置系统范围的默认值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我试图设置使用UDP发送数据包的DF(不分段标志).

看看Richard Steven的书第1卷Unix网络编程;套接字网络API,我无法找到如何设置它.

我怀疑我会用setsockopt()来做,但是在第193页的表格中找不到它.

请建议如何做到这一点.

解决方法:

你可以通过使用IP_DONTFRAG选项调用setsockopt()来实现::

int val = 1;

setsockopt(sd, IPPROTO_IP, IP_DONTFRAG, &val, sizeof(val));

Here’s页面进一步详细解释了这一点.

对于Linux,您似乎必须使用IP_MTU_DISCOVER选项,其值为IP_PMTUDISC_DO(或IP_PMTUDISC_DONT以将其关闭):

int val = IP_PMTUDISC_DO;

setsockopt(sd, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val));

我没有测试过这个,只是查看了头文件和一些网页搜索,所以你需要测试它.

至于是否可以设置DF标志的另一种方式:

I find nowhere in my program where the “force DF flag” is set, yet tcpdump suggests it is. Is there any other way this could get set?

从这个优秀的页面here:

IP_MTU_DISCOVER: Sets or receives the Path MTU Discovery setting for a socket. When enabled, Linux will perform Path MTU Discovery as defined in RFC 1191 on this socket. The don’t fragment flag is set on all outgoing datagrams. The system-wide default is controlled by the ip_no_pmtu_disc sysctl for SOCK_STREAM sockets, and disabled on all others. For non SOCK_STREAM sockets it is the user’s responsibility to packetize the data in MTU sized chunks and to do the retransmits if necessary. The kernel will reject packets that are bigger than the known path MTU if this flag is set (with EMSGSIZE).

这对我来说就像你可以使用sysctl设置系统范围的默认值:

sysctl ip_no_pmtu_disc

在我的系统上返回“错误:”ip_no_pmtu_disc“是一个未知的密钥”,但它可能会在你的系统上设置.除此之外,我不知道可能影响设置的任何其他东西(除了之前提到的setsockopt()).

标签:packet,c,sockets,udp

来源: https://codeday.me/bug/20190925/1815864.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值