- 论坛徽章:
- 0
|
回复 #5 urapple 的帖子
#define TIMEOUT 3
int _connect( const char* servip)
{
int fd, retval;
struct sockaddr_in addr;
struct timeval timeo = { TIMEOUT,0};
socklen_t len = sizeof(timeo);
fd_set set;
int savefl = 0;
fd = socket(AF_INET, SOCK_STREAM, 0);
savefl = fcntl( fd,F_GETFL);
fcntl( fd, F_SETFL, savefl | O_NONBLOCK);
bzero( &addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(servip);
addr.sin_port = htons( 1241);
if( connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == 0)
goto sjmp;
if( errno != EINPROGRESS)
{
perror("connect: ");
goto fjmp;
}
FD_ZERO( &set);
FD_SET( fd, &set);
retval = select( fd + 1, NULL, &set, NULL, &timeo);
if( retval < 0)
{
perror( "select");
goto fjmp;
}
else if( retval == 0)
{
fprintf( stderr, "select timeout\n");
goto fjmp;
}
if( FD_ISSET( fd, &set))
{
int error = 0;
socklen_t len = sizeof( error);
if( getsockopt( fd, SOL_SOCKET, SO_ERROR, &error, &len) < 0)
{
fprintf( stderr, "getsockopt fail,connected fail\n");
goto fjmp;
}
if( error == ETIMEDOUT)
{
fprintf( stderr, "connecte timeout\n");
goto fjmp;
}
if( error == 0)
goto sjmp;
else
{
fprintf( stderr, "connect error.\n ");
goto fjmp;
}
}
fjmp:
close(fd);
return -1;
sjmp:
fcntl( fd, F_SETFL, savefl);
GlobalSocket = fd;
return fd;
} |
|