Search in shivacherukuri.tech@blogger.com

Thursday, March 18, 2010

Using setsockopt


#//using setsockopt

#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>

void
usage()
{
    printf("usage: setsock [-s <size>]\n");
    exit(1);
}

main(argc,argv)
int argc;
char **argv;
{
    char           c;
    unsigned int   ksize;
    int            fd;
    int            ret;
    unsigned long  size;
    socklen_t      len;

    while (( c = getopt (argc, argv, "s:")) != EOF) {
        switch (c) {
           case 's':
               ksize = atoi(optarg);
               break;
           default:
               usage();
        }
    }

    fd = socket(AF_INET, SOCK_STREAM, 0);
    if (-1 == fd) {
        printf("socket call failed.\n");
        exit(1);
    }

    size = ksize * 1024;

    ret = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (void *)&size, sizeof(size));
    if (0 == ret) {
        printf("Successfully set the socket send buf size to %lu\n", size);
        len = sizeof(size);
        ret = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, (void *)&size,
                         (int *)&len);
        printf("getsockopt ret is %d. errno is %d. len is %d, "
               "size is %lu\n", ret,
               errno, len, size);
        exit(0);
    }

    printf("Failed to set the socket send buf size to %lu.  "
           "ret = %d, errno = %d.\n",
           ret, size, errno);
        ret = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, (void *)&size,
                         (int *)&len);
        printf("getsockopt ret is %d. errno is %d. len is %d, "
               "size is %lu\n", ret,
               errno, len, size);
    exit(1);
}

No comments:

Post a Comment