C++自定义connect超时时间——非阻塞套接字法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/89428900

一 代码

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <time.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <string.h>

#define BUFFER_SIZE 1023

int setnonblocking( int fd )     //设置套接字为非阻塞套接字
{
    int old_option = fcntl( fd, F_GETFL );
    int new_option = old_option | O_NONBLOCK;
    fcntl( fd, F_SETFL, new_option );
    return old_option;
}

int unblock_connect( const char* ip, int port, int time )
{
    int ret = 0;
    struct sockaddr_in address;
    bzero( &address, sizeof( address ) );
    address.sin_family = AF_INET;
    inet_pton( AF_INET, ip, &address.sin_addr );
    address.sin_port = htons( port );

    int sockfd = socket( PF_INET, SOCK_STREAM, 0 );
    int fdopt = setnonblocking( sockfd );      //套接字设置为非阻塞套接字     
    ret = connect( sockfd, ( struct sockaddr* )&address, sizeof( address ) );
    printf("connect ret code = %d\n", ret);
    if ( ret == 0 )
    {
        printf( "connect with server immediately\n" );
        fcntl( sockfd, F_SETFL, fdopt );   //set old optional back
        return sockfd;
    }
    //unblock mode --> connect return immediately! ret = -1 & errno=EINPROGRESS
    else if ( errno != EINPROGRESS )
    {
        printf("ret = %d\n", ret);
        printf( "unblock connect failed!\n" );
        return -1;
    }
    else if (errno == EINPROGRESS)
    {
        printf( "unblock mode socket is connecting...\n" );
    }

    //use select to check write event, if the socket is writable, then
    //connect is complete successfully!
    fd_set readfds;
    fd_set writefds;
    struct timeval timeout;

    FD_ZERO( &readfds );
    FD_SET( sockfd, &writefds );

    timeout.tv_sec = time; //我们设置超时时间为1秒,原来大概需要3秒
    timeout.tv_usec = 0;

    ret = select( sockfd + 1, NULL, &writefds, NULL, &timeout );
    if ( ret <= 0 )
    {
        printf( "connection time out\n" );
        close( sockfd );
        return -1;
    }

    if ( ! FD_ISSET( sockfd, &writefds  ) )
    {
        printf( "no events on sockfd found\n" );
        close( sockfd );
        return -1;
    }

    int error = 0;
    socklen_t length = sizeof( error );
    if( getsockopt( sockfd, SOL_SOCKET, SO_ERROR, &error, &length ) < 0 )
    {
        printf( "get socket option failed\n" );
        close( sockfd );
        return -1;
    }

    if( error != 0 )
    {
        printf( "connection failed after select with the error: %d \n", error );
        close( sockfd );
        return -1;
    }

    //connection successful!
    printf( "connection ready after select with the socket: %d \n", sockfd );
    fcntl( sockfd, F_SETFL, fdopt ); //set old optional back
    return sockfd;
}

int main( int argc, char* argv[] )
{
    if( argc <= 2 )
    {
        printf( "usage: %s ip_address port_number\n", basename( argv[0] ) );
        return 1;
    }
    const char* ip = argv[1];
    int port = atoi( argv[2] );

    int sockfd = unblock_connect( ip, port, 1);  //这个值可以修改为5秒作测试
    if ( sockfd < 0 )
    {
        printf("sockfd error! return -1\n");
        return 1;
    }
    //shutdown( sockfd, SHUT_WR ); //disable read and write
    printf( "send data out\n" );
    send( sockfd, "abc", 3, 0 );
    shutdown( sockfd, SHUT_WR ); //disable read and write
    close(sockfd);
    return 0;
}

二 运行

[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test 192.168.0.111 11133 kkk              //该IP不存在
connect ret code = -1
unblock mode socket is connecting...
connection time out
sockfd error! return -1
[root@localhost test]# ./test 192.168.0.110 11133 kkk              //该IP是本机IP
connect ret code = -1
unblock mode socket is connecting...
connection failed after select with the error: 111
sockfd error! return -1

如果把超时时间修改为5秒

[root@localhost test]# ./test 192.168.0.112 11133 kkk
connect ret code = -1
unblock mode socket is connecting...
connection failed after select with the error: 113
sockfd error! return -1

三 说明

1 SO_ERROR参考

https://blog.csdn.net/feng973/article/details/53463750

2 常见SO_ERROR

#define ECONNREFUSED    111 /* Connection refused */
#define EHOSTDOWN   112 /* Host is down */
#define EHOSTUNREACH    113 /* No route to host */

3 代码中自定义函数setnonblocking,用于设置套接字为非阻塞套接字。然后定义一个函数unblock_connect用于连接,并且设置为1秒作为超时时间。而实际的超时返回是通过select函数来实现的。

192.168.0.111是Linux主机IP的同一网段的一个假IP,原来阻塞超时3秒作用,所以修改为1秒后,会走超时分支,说明我们自定义的超时生效了。

192.168.0.110是本机IP,它返回的错误码是111,拒绝连接。

192.168.0.111是Linux主机IP的同一网段的一个假IP,把代码的超时时间从1秒改为5秒,连接错误码是113,即没有路由到主机。

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/89428900