Linux 对于 C 中的 IPPROTO_TCP IP_TOS,setsockopt 失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6141463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 04:17:22  来源:igfitidea点击:

setsockopt fails for IPPROTO_TCP IP_TOS in C

clinuxsocketsnetwork-programming

提问by cateof

My code fails. I am running as root (same behavior as normal user)

我的代码失败了。我以 root 身份运行(与普通用户相同的行为)

First I want to set the TOS and then get the value.

首先我想设置 TOS,然后获取值。

int tos_local = 0x28;
if (setsockopt(sockfd, IPPROTO_TCP, IP_TOS,  &tos_local, sizeof(tos_local))) {
    error("error at socket option");
} else {
    int tos=0;
    int toslen=0;

    if (getsockopt(sockfd, IPPROTO_TCP, IP_TOS,  &tos, &toslen) < 0) {
            error("error to get option");
    }else {
            printf ("changing tos opt = %d\n",tos);
    }
}

the printf prints

printf 打印

changing tos opt = 0

改变 tos opt = 0

I would expect to print 0x28 (40).

我希望打印 0x28 (40)。

What is the problem?

问题是什么?

The correct answer:

正确答案:

    if (setsockopt(sockfd, **IPPROTO_IP**, IP_TOS,  &tos_local, sizeof(tos_local))) {

    int tos=0;
    int toslen=sizeof(tos); //that line here

    if (getsockopt(sockfd, IPPROTO_IP, IP_TOS,  &tos, &toslen) < 0) {

采纳答案by Ben Voigt

IP_TOShas level IPPROTO_IP, not IPPROTO_TCP.

IP_TOS有水平IPPROTO_IP,没有IPPROTO_TCP

See the documentation.

请参阅文档

This affects both setting and getting the option.

这会影响设置和获取选项。

Also, what Seth said about initializing the length parameter, which affects only getsockopt.

此外,赛斯所说的关于初始化长度参数的内容仅影响getsockopt.

回答by Seth Robertson

When calling getsockopt, you pass in the size of the memory pointed to by &tos. In other words initialize toslen to sizeof(tos).

调用getsockopt 时,传入&tos 指向的内存大小。换句话说,将 toslen 初始化为 sizeof(tos)。