First of all I would like to say that this is another problem than this one: Similar but not the same
My code looks like this:
struct addrinfo hints, *res;
struct sockaddr* serveraddr;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
int res2 = getaddrinfo(ip, port, &hints, &res);
printf("getaddrinfo() res: %d, %d
", res2, errno);
serveraddr = res->ai_addr;
//create new socket
int soc = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
printf("socket() res: %d, %d
", socket, errno);
//set nonblocking mode
unsigned long on = 1;
res2 = ioctl(soc, FIONBIO, &on);
printf("ioctl() res: %d
, %d", res2, errno);
res2 = connect(soc, serveraddr, sizeof(struct sockaddr));
printf("connect() res: %d, %d
", res2, errno);
//check if socket is ready
fd_set wfds;
FD_ZERO(&wfds);
FD_SET(soc, &wfds);
struct timeval t;
t.tv_sec=15;
t.tv_usec=0;
res2 = select(soc + 1, 0, &wfds, 0, &t);
printf("select() res: %d, %d
", res2, errno);`
I'm connecting to machine that exists (IP address exists, but there is no server listening on port I'm trying to connect).
Select always returns 1. Why? According to man it should timeout and return 0.
After this when I try to write something to socket it returns -1/ECONNREFUSED.
Is this expected behaviour? If yes, how to check after select() is we are connected?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…