对于C中的IPPROTO_TCP IP_TOS,setsockopt失败

cat*_*eof 6 c sockets linux network-programming

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

首先,我想设置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);
    }
}
Run Code Online (Sandbox Code Playgroud)

printf打印

改变tos opt = 0

我希望打印0x28(40).

问题是什么?

正确答案:

    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) {
Run Code Online (Sandbox Code Playgroud)

Ben*_*igt 6

IP_TOS有水平IPPROTO_IP,而不是IPPROTO_TCP.

请参阅文档.

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

此外,Seth所说的初始化长度参数,仅影响getsockopt.