I would like to use the following example to timeout a connection attempt, made by a TCP socket:
Code:
/*
** select.c -- a select() demo
*/
#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#define STDIN 0 // file descriptor for standard input
int main(void){
struct timeval tv;
fd_set readfds;
tv.tv_sec = 2;
tv.tv_usec = 500000;
FD_ZERO(&readfds);
FD_SET(STDIN, &readfds);
// don't care about writefds and exceptfds:
select(STDIN+1, &readfds, NULL, NULL, &tv);
if (FD_ISSET(STDIN, &readfds))
printf("A key was pressed!\n");
else
printf("Timed out.\n");
return 0;
}
my socket function looks like this:
Code:
int checkprt(int port, char *ip){
int test = 0;
int sockfd;
struct sockaddr_in servaddr;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0) {
printf("error. cannot creat socket\n");
return ERROR;
}
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr(ip);
servaddr.sin_port = htons(port);
test = connect(sockfd, (struct sockaddr_in *)&servaddr, sizeof(servaddr));
if(test == -1){
close(sockfd);
return CLOSED;
}
close(sockfd);
return OPEN;
}
As you probably have guessed I am in the middle of learning socket programming. Any help here on how to use the select() example to timeout a connect attempt would be appreciated.