Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setsockopt fails for IPPROTO_TCP IP_TOS in C

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

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

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

changing tos opt = 0

I would expect to print 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) {
like image 547
cateof Avatar asked May 26 '11 15:05

cateof


2 Answers

IP_TOS has level IPPROTO_IP, not 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.

like image 171
Ben Voigt Avatar answered Nov 11 '22 08:11

Ben Voigt


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

like image 32
Seth Robertson Avatar answered Nov 11 '22 08:11

Seth Robertson