c - C 中的 IPPROTO_TCP IP_TOS 的 setsockopt 失败

标签 c linux sockets 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);
    }
}

printf 打印

changing 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) {

最佳答案

IP_TOS 具有级别 IPPROTO_IP,而不是 IPPROTO_TCP

参见 the documentation .

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

此外,Seth 所说的关于初始化长度参数的内容,它只影响 getsockopt

关于c - C 中的 IPPROTO_TCP IP_TOS 的 setsockopt 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6141463/

相关文章:

c - 如何读取内核空间中关联的 uid 的 gids 列表?

c - 在不交换数据的情况下交换链表中的节点

c - 新Linux内核的epoll是否还存在惊群问题?

linux - bash if 语句问题

c - 如何在套接字上使用 lex 扫描器?

java - 通过套接字发送可执行 Java

c++ - 生成用户定义素数的相对素数?

c - 结构单向链表。为什么这不起作用?

java - 跨平台使用带目录的程序

c sendto函数在linux2.6.29中设置 “network is unreachable” errno