码迷,mamicode.com
首页 > Web开发 > 详细

network

时间:2014-07-16 00:21:46      阅读:331      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   div   时间   re   

#include <sys/types.h>      
#include <sys/socket.h>
#include <fcntl.h>
#include <unistd.h>
#include <netinet/tcp.h>
#include "server_network.h"

int sock_setnonblock(sock_t s)
{
    int flags = 0;
    flags = fcntl(s, F_GETFL);
    if (flags < 0)
        return flags;
    
    flags |= O_NONBLOCK;
    if (fcntl(s, F_SETFL, flags) < 0)
        return -1;

    return 0;
}


int sock_unsetnonblock(sock_t s)
{
    int flags = 0;
    flags = fcntl(s, F_GETFL);
    if (flags < 0)
        return flags;

    flags &= ~O_NONBLOCK;
    if (fcntl(s, F_SETFL, flags) < 0)
        return -1;

    return 0;
}


int sock_setnodelay(sock_t s)
{
    int flag =1;
    return setsockopt(s, SOL_TCP, TCP_NODELAY, (char *)&flag, sizeof(flag));
}


int sock_set_recv_timeout(sock_t s, int sec)
{
    struct timeval timeout;

    timeout.tv_sec = sec;
    timeout.tv_usec = 0;

    return setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,
                  sizeof(timeout));    
}

int sock_set_snd_timeout(sock_t s, int sec)
{
    struct timeval timeout;

    timeout.tv_sec = sec;
    timeout.tv_usec = 0;

    return setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout,
                  sizeof(timeout));
}


int sock_set_keepalive(sock_t s, int timeout)
{
    int val = 1;
    //设置成keepalive模式
    if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &val, sizeof(val)) < 0) {
        return -1;
    }
    //设置探测时间
    val = timeout;
    if (setsockopt(s, SOL_TCP, TCP_KEEPIDLE, &val, sizeof(val)) < 0) {
        return -1;
    }
    //设置探测间隔时间,1s
    val = 1;
    if (setsockopt(s, SOL_TCP, TCP_KEEPINTVL, &val, sizeof(val)) < 0) {
        return -1;
    }
    //设置探测次数,3次
    val = 3;
    if (setsockopt(s, SOL_TCP, TCP_KEEPCNT, &val, sizeof(val)) < 0) {
        return -1;
    }
    return 0;
}

 

network,布布扣,bubuko.com

network

标签:style   blog   color   div   时间   re   

原文地址:http://www.cnblogs.com/unixshell/p/3844922.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!