/************************************************************ * * Trivial example of how to use a non-blocking * connect() * * (c) Bob Krouse, 2005. * * GPL * *************************************************************/ #include #include #include #include #include #include #include #include #include #include int main(int argc, char **argv) { int ret, fd; fd_set desc_set; struct sockaddr_in addr; struct timeval timeout; timeout.tv_sec = 10; timeout.tv_usec = 0; fd = socket(PF_INET, SOCK_STREAM, 0); printf("Connecting..."); fflush(NULL); fcntl(fd, F_SETFL, O_NONBLOCK); FD_ZERO(&desc_set); FD_SET(fd, &desc_set); memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr("24.36.29.100"); addr.sin_port = htons(80); ret = connect(fd, (struct sockaddr*)&addr, sizeof(addr)); if(ret == -1) { ret = select(fd+1, NULL, &desc_set, NULL, &timeout); if(ret == 0) { printf("Timed Out!\n"); exit(1); } if(FD_ISSET(fd, &desc_set)) { printf("Connected\n"); } } return 1; }