代码之家  ›  专栏  ›  技术社区  ›  adhanlon

在C中使用connect()时设置超时++

  •  3
  • adhanlon  · 技术社区  · 16 年前

    using namespace std;
    int main( int argc, char* argv[] )
    {
      // Interpret the command line arguments
      string uri_string = "";
    
      if ( argc != 2 )
      {
        cerr << "Usage: " << argv[0];
        cerr << " <URI>" << endl;
        return 1;
      }
      else
      {
        uri_string = argv[1];
      }
    
      // Create URI object and have it parse the uri_string
      URI *uri = URI::Parse(uri_string);
    
      if ( uri == NULL )
      {
        cerr << "Error: Cannot parse URI." << endl;
        return 2;
      }
    
      // Check the port number specified, if none use port 80
      unsigned port = 80;
      if ( uri->Is_port_defined() )
      {
        port = uri->Get_port();
      }
    
      // Create TCP socket and connect to server
      int tcp_sock = socket( AF_INET, SOCK_STREAM, 0 );
      if ( tcp_sock < 0 )
      {
        cerr << "Unable to create TCP socket." << endl;
        return 3;
      }
    
      sockaddr_in server;
      socklen_t slen = sizeof(server);
    
      server.sin_family = AF_INET;
      server.sin_port = htons( port );
      cout << "Resolving " << uri->Get_host() << "... ";
      hostent *hostp = gethostbyname( uri->Get_host().c_str() );
      memcpy( &server.sin_addr, hostp->h_addr, hostp->h_length );
    
      struct in_addr **pptr;
      pptr = (struct in_addr **)hostp->h_addr_list;
    
      string ip_addr = "";
      while( *pptr != NULL ) {
        ip_addr += inet_ntoa(**(pptr++));
      }
      cout << ip_addr << endl;
    
      cout << "Connecting to " << uri->Get_host() << "|" << ip_addr << "|:";
      cout << port << "... ";
      if ( connect( tcp_sock, (sockaddr*)&server, slen ) < 0 )
      {
        cerr << "Unable to connect to server via TCP." << endl;
        close( tcp_sock );
        return 4;
      }
      cout << "connected." << endl;
    
      // rest of code
    }
    
    4 回复  |  直到 9 年前
        1
  •  7
  •   janm    16 年前

    将套接字设置为非阻塞套接字,然后使用带有超时值的select()或poll()来检查可写性。如果select()返回超时,则表示您没有及时连接,您可以关闭套接字并处理连接失败。如果它返回并完成,则一切正常,您可以继续。

        2
  •  1
  •   elder_george    16 年前

    为套接字设置非阻塞模式并使用 select 检查连接是否建立。 here 是样品吗

        3
  •  1
  •   Rantaak    16 年前

    另一种不需要select()痛苦的非阻塞方法是检查EWOULDBLOCK的GetLastError()。

    // set socket as nonblocking
    unsigned long value = 1;
    if (ioctlsocket(yourSocket, FIONBIO, &value) == SOCKET_ERROR)
        return SOCKET_ERROR;
    
    // (call connect here)
    
    // check if connect would block
    if (GetLastError() == EWOULDBLOCK)
        return TIMEOUT;
    
        4
  •  1
  •   Justin Grant    6 年前

    看一看 this newsgroup post ,详细介绍了如何在Linux中为套接字连接设置超时。基本思想是使用非阻塞套接字,然后等待连接。