int myconnect(int fd, const struct sockaddr *name, int namelength, int seconds)
{
fd_set fds1, fds2;
struct timeval tv;
int result = -1;
int flags;
socklen_t len;
// 先设置为非阻塞模式
flags = fcntl(fd, F_GETFL, 0);
if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) >= 0)
{
result = connect(fd, name, namelength);
if (result != 0 && errno == EINPROGRESS)
{
FD_ZERO(&fds1);
FD_ZERO(&fds2);
FD_SET(fd, &fds1);
FD_SET(fd, &fds2);
tv.tv_sec = seconds;
tv.tv_usec = 0;
switch (select(fd + 1, NULL, &fds1, &fds2, &tv))
{
case -1:
case 0:
break;
{
if (FD_ISSET(fd, &fds1))
{
len = sizeof(int);
if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &result, &len) < 0)
{
result = -1;
}
}
}
break;
}
}
// 还原 为阻塞模式
fcntl(fd, F_SETFL, flags);
}
return(result);
{
fd_set fds1, fds2;
struct timeval tv;
int result = -1;
int flags;
socklen_t len;
// 先设置为非阻塞模式
flags = fcntl(fd, F_GETFL, 0);
if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) >= 0)
{
result = connect(fd, name, namelength);
if (result != 0 && errno == EINPROGRESS)
{
FD_ZERO(&fds1);
FD_ZERO(&fds2);
FD_SET(fd, &fds1);
FD_SET(fd, &fds2);
tv.tv_sec = seconds;
tv.tv_usec = 0;
switch (select(fd + 1, NULL, &fds1, &fds2, &tv))
{
case -1:
case 0:
break;
default:
// 这里的判断很重要,网上例子大多没有这部分
if (!FD_ISSET(fd, &fds2)){
if (FD_ISSET(fd, &fds1))
{
len = sizeof(int);
if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &result, &len) < 0)
{
result = -1;
}
}
}
break;
}
}
// 还原 为阻塞模式
fcntl(fd, F_SETFL, flags);
}
return(result);
}