#include #include #include #include #include #include #include #include #include #include #define SERVER_HOST "127.0.0.1" #define SERVER_PORT 12345 int main() { int sockfd; struct sockaddr_in server_addr; fd_set write_fds; struct timeval timeout; int flags, result; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd == -1) { perror("socket"); return 1; } memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(SERVER_PORT); if (inet_pton(AF_INET, SERVER_HOST, &server_addr.sin_addr) <= 0) { perror("inet_pton"); close(sockfd); return 1; } flags = fcntl(sockfd, F_GETFL, 0); if (flags == -1) { perror("fcntl"); close(sockfd); return 1; } if (fcntl(sockfd, F_SETFL, flags | O_NONBLOCK) == -1) { perror("fcntl"); close(sockfd); return 1; } result = connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)); if (result < 0 && errno != EINPROGRESS) { perror("connect"); close(sockfd); return 1; } printf("Trying to connect...\n"); while (1) { FD_ZERO(&write_fds); // FD_SET(sockfd, &write_fds); timeout.tv_sec = 0; timeout.tv_usec = 100000; result = select(sockfd + 1, NULL, &write_fds, NULL, &timeout); if (result == -1) { perror("select"); close(sockfd); return 1; } if (FD_ISSET(sockfd, &write_fds)) { printf("Successfully connected to %s:%d\n", SERVER_HOST, SERVER_PORT); break; } else { printf("Still attempting to connect...\n"); sleep(1); } } close(sockfd); return 0; }