#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <errno.h> #include <time.h>
int main(int argc, char *argv[]) { int fd, retval; struct sockaddr_in addr; struct timeval timeo = {3, 0}; socklen_t len = sizeof(timeo); fd_set set;
fd = socket(AF_INET, SOCK_STREAM, 0); if (argc == 4) timeo.tv_sec = atoi(argv[3]); fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK); addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr(argv[1]); addr.sin_port = htons(atoi(argv[2])); printf("%d\n", time(NULL)); if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == 0) { printf("connected\n"); return 0; } if (errno != EINPROGRESS) { perror("connect"); return -1; } FD_ZERO(&set); FD_SET(fd, &set); retval = select(fd + 1, NULL, &set, NULL, &timeo); if (retval == -1) { perror("select"); return -1; } else if(retval == 0) { fprintf(stderr, "timeout\n"); printf("%d\n", time(NULL)); return 0; } printf("connected\n");
return 0; }
|