I could have sworn I got this working at one point but I must of misplaced the code and I never added it to my socket class I use now instead of having to redo the whole socket handling each and every time.

I got this part working:
Code:
		int flags = fcntl(sockfd,F_GETFL,0);
		fcntl(sockfd,F_SETFL, flags | O_NONBLOCK);

But there is a loop of some sort I have to do using Sleep() until I reach a certain amount of interations, and think I also have to use select() somewhere.

I just can't seem to peiece it all together and online resources have not been very helpful and showing a complete program making use of this.

Basically, I want connect() to timeout after like 5 seconds. By default it just sits there forever. Oddly, I've seen times where it does not. It seems to be very random. I want it to wait 5 seconds no matter what. If it can't connect, it returns error, and my program can move on.


With the above code I have it where it fails each time now, so I am getting somewhere... My entire code is this:

Code:
    bool SocketClient::Connect()
    {
    	#ifdef WIN32
        WSADATA  wsaData;
        if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) {
            fprintf(stderr, "WSAStartup failed.\n");
            exit(1);
        }	
    	#endif
    	
    
    
        sockfd = socket(PF_INET, SOCK_STREAM, 0);
    
        if ((he=gethostbyname(ip.c_str())) == NULL) {  // get the host info 
    		status=2;
            return false;
        }	
    	
        dest_addr.sin_family = AF_INET;          // host byte order
        dest_addr.sin_port = htons(port);   // short, network byte order
    	dest_addr.sin_addr = *((struct in_addr *)he->h_addr);
        memset(dest_addr.sin_zero, '\0', sizeof dest_addr.sin_zero);
    
	
		//set non blocking mode:
		int flags = fcntl(sockfd,F_GETFL,0);
		fcntl(sockfd,F_SETFL, flags | O_NONBLOCK);
    	
		//connect:
        int res = connect(sockfd, (struct sockaddr *)&dest_addr, sizeof dest_addr);	
    		if(res==-1)
    		{
    		status=2;
    		return false;
    		}
			
		#ifdef WIN32
		//enable non blocking sockets for win32:
		u_long arg = 1;
		ioctlsocket(sockfd, FIONBIO, &arg);	
		#endif			
    
    	status=1;
    		
        return true;
    }