Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
548 views
in Technique[技术] by (71.8m points)

c - In a non blocking socket connect, select() always returns 1

I have this code segment that is designed to connect to a server using a socket connection. However if it can not connect to the server within a certain amount of time I would like it to stop trying. I tried to do this with this nonblocking socket and the select command but select is always returning 1 indicating that the server exists when nothing exists at the address I give it. Any Ideas?

SOCKET tcp_client( char *hname, char *sname )  {    
    fd_set fdset;
    struct sockaddr_in peer;
    SOCKET s;
    FD_ZERO(&fdset);
    // FD_SET(STDIN, &fdset);
    FD_SET(s, &fdset);
    errno=1;
    struct timeval tv;
    tv.tv_sec = 15;
    set_address( hname, sname, &peer, "tcp" );
    s = socket( AF_INET, SOCK_STREAM, 0 );

    int n = 1;
    fcntl(s, F_SETFL, O_NONBLOCK);

    if ( !isvalidsock( s ) )
    {
        printf("Socket Call Failed: %s
", strerror(errno));
        return(0);
    }

    int x = 0;

    int status = connect( s, ( struct sockaddr * )&peer, sizeof( peer ) );

    if(status < 0) {
        printf("Status: %i
", status); 
    }

    int retVal = select(s+1, &fdset, NULL, NULL, &tv);
    printf("retVal: %i
", retVal);

    if (retVal == 1) {
        int so_error;
        socklen_t slen = sizeof so_error;
        getsockopt(s, SOL_SOCKET, SO_ERROR, &so_error, &slen);
        if (so_error == 0) {
            printf("work
");

            x =1;
        } else {
            printf("fail
");
            x = 0;
        }
    } else {     
        printf("noSocks
"); 
    }


    if (x ==0 )
    {
        printf("Connect Failed: %s
", strerror(errno));
        L("libOnexc: Connect to socket failed");
        close(s);
        return(0);
    } 

    return s;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to check whether the socket is ready for writing (the second fd_set * argument to select), not reading (the first one).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...