Example C code to set TOS on a socket 

Joined:
04/19/2010
Posts:
98

October 08, 2014 11:29:18    Last update: October 08, 2014 11:29:18
Example C code to set the "Type Of Service" (TOS) field, lifted from http://stackoverflow.com/questions/11429403/how-to-set-message-priority-using-tos.

#include <string.h>
#include <netdb.h>

int main(int argc, char**argv)
{
   int listenfd, connfd, optval;
   struct sockaddr_in servaddr, cliaddr;
   socklen_t clilen;
   pid_t     childpid;
   char      mesg[16];

   listenfd = socket(AF_INET, SOCK_STREAM, 0);

   bzero(&servaddr, sizeof(servaddr));
   bzero(mesg, sizeof(mesg));
   servaddr.sin_family = AF_INET;
   servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
   servaddr.sin_port = htons(32000);
   bind(listenfd,(struct sockaddr *)&servaddr, sizeof(servaddr));

   listen(listenfd, 1024);

   for (;;)
   {
      clilen = sizeof(cliaddr);
      connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen);

      if ((childpid = fork()) == 0)
      {
         close(listenfd);

         for (;;)
         {
            optval = 0x28;
            setsockopt(connfd, IPPROTO_IP, IP_TOS, &optval, sizeof(optval));
            strcpy(mesg, "tos=0x28");
            sendto(connfd, mesg, sizeof(mesg), 0, (struct sockaddr *)&cliaddr, sizeof(cliaddr));
            sleep(2);

            optval = 0x58;
            strcpy(mesg, "tos=0x58");
            setsockopt(connfd, IPPROTO_IP, IP_TOS, &optval, sizeof(optval));
            sendto(connfd, mesg, sizeof(mesg), 0, (struct sockaddr *)&cliaddr, sizeof(cliaddr));
            sleep(2);
         }

      }

      close(connfd);
   }
}
Share |
| Comment  | Tags