socket connect 函数设置超时

来源:互联网 发布:网站源码免费下载 编辑:程序博客网 时间:2024/05/16 19:18

众所周知,在进行网络编程的时候,如果使用系统connect函数,无法设置超时,而在连接一个不存在的主机时,将会一直阻塞。

其实在调用connect函数时,将句柄设置为非阻塞,然后调用select函数,可以达到设置超时的效果。


[cpp] view plaincopyprint?
  1. bool connect(char *host,int port,int timeout)
  2. {
  3. TIMEVAL Timeout;
  4. Timeout.tv_sec = timeout;
  5. Timeout.tv_usec = 0;
  6. struct sockaddr_in address; /* the libc network address data structure */
  7. sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  8. address.sin_addr.s_addr = inet_addr(host); /* assign the address */
  9. address.sin_port = htons(port); /* translate int2port num */
  10. address.sin_family = AF_INET;
  11. //set the socket in non-blocking
  12. unsigned long iMode = 1;
  13. int iResult = ioctlsocket(sock, FIONBIO, &iMode);
  14. if (iResult != NO_ERROR)
  15. {
  16. printf("ioctlsocket failed with error: %ld\n", iResult);
  17. }
  18. if(connect(sock,(struct sockaddr *)&address,sizeof(address))==false)
  19. {
  20. return false;
  21. }
  22. // restart the socket mode
  23. iMode = 0;
  24. iResult = ioctlsocket(sock, FIONBIO, &iMode);
  25. if (iResult != NO_ERROR)
  26. {
  27. printf("ioctlsocket failed with error: %ld\n", iResult);
  28. }
  29. fd_set Write, Err;
  30. FD_ZERO(&Write);
  31. FD_ZERO(&Err);
  32. FD_SET(sock, &Write);
  33. FD_SET(sock, &Err);
  34. // check if the socket is ready
  35. select(0,NULL,&Write,&Err,&Timeout);
  36. if(FD_ISSET(sock, &Write))
  37. {
  38. return true;
  39. }
  40. return false;
  41. }