蓝天

测试setsockopt设置超时是否生效代码

// 测试setsockopt设置超时是否生效代码
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

// 编译:
// g++ -g -o x x.cpp
int main()
{
    // 创建一个客户端TCP socket
    int fd = socket(PF_INET, SOCK_STREAM, 0);
    if (-1 == 0)
    {
        perror("socket");
        exit(1);
    }

    // 设定目标地址
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(9090); // 确保这个端口是打开的
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    memset(addr.sin_zero, 0, sizeof(addr.sin_zero));
    int ret = connect(fd, (const struct sockaddr *)&addr, sizeof(addr));
    if (ret != 0)
    {
        perror("connect");
        exit(1);
    }

    // 设置recv超时
    struct timeval timeout;
    timeout.tv_sec = 6; // 设定6秒超时
    timeout.tv_usec = 0;    
    ret = setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
    if (ret != 0)
    {
        perror("setsockopt");
        exit(1);
    }

    // 调用recv,期望预期的时间内超时
    char buf[4096];
    //ret = recv(fd, buf, sizeof(buf), 0);
    ret = read(fd, buf, sizeof(buf));
    printf("%d: %m\n", ret); // 期待结果:-1: Resource temporarily unavailable

    close(fd);
    return 0;
}

posted on 2016-05-12 14:55  #蓝天  阅读(1168)  评论(0编辑  收藏  举报

导航