123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <fcntl.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <errno.h>
- #include <string.h>
- #include <sys/select.h>
- #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;
- }
|