Set timeout for winsock recvfrom

后端 未结 4 1586
野性不改
野性不改 2020-12-05 19:13

I\'m trying to set up a blocking socket to timeout after 16 ms of trying to recvfrom() on a port. Platform is Windows. I\'ve looked at tons of examples online and it seems

相关标签:
4条回答
  • 2020-12-05 19:24

    WINDOWS: Timeout value is a DWORD in milliseconds, address passed to setsockopt() is const char *

    LINUX: Timeout value is a struct timeval, address passed to setsockopt() is const void *

    Source: http://forums.codeguru.com/showthread.php?t=353217

    0 讨论(0)
  • 2020-12-05 19:38

    I'm guessing Windows from the WSASocket() call. If so you're passing the timeout incorrectly.

    MSDN says that SO_RCVTIMEO takes an int param that specifies the timeout in ms.

    0 讨论(0)
  • 2020-12-05 19:46

    I looked into the select function and as laura said I should do and got it to work real easily! Thanks!

    fd_set fds ;
    int n ;
    struct timeval tv ;
    
    // Set up the file descriptor set.
    FD_ZERO(&fds) ;
    FD_SET(mHandle, &fds) ;
    
    // Set up the struct timeval for the timeout.
    tv.tv_sec = 10 ;
    tv.tv_usec = 0 ;
    
    // Wait until timeout or data received.
    n = select ( mHandle, &fds, NULL, NULL, &tv ) ;
    if ( n == 0)
    { 
      printf("Timeout..\n");
      return 0 ;
    }
    else if( n == -1 )
    {
      printf("Error..\n");
      return 1;   
    }
    
    int length = sizeof(remoteAddr);
    
    recvfrom(mHandle, buffer, 1024, 0, (SOCKADDR*)&remoteAddr, &length); 
    
    0 讨论(0)
  • 2020-12-05 19:48

    I tried it by passing it like the folloing

         int iTimeout = 1600;
         iRet = setsockopt( pSapManager->m_cSocket,
                            SOL_SOCKET,
                            SO_RCVTIMEO,
                            /*
                            reinterpret_cast<char*>(&tv),
                            sizeof(timeval) );
                            */
                            (const char *)&iTimeout,
                            sizeof(iTimeout) );
    

    and run it!!

    0 讨论(0)
提交回复
热议问题