• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 5866
  • Last Modified:

how to setup socket timeout?

I can make a socket listen on a port, but I don't know how to make it timeout if it doesn't recieve any data on that port within, say, 10 seconds.

Does anyone know where I'm going wrong?



SOCKET sock = INVALID_SOCKET;
sock = socket ( AF_INET, SOCK_DGRAM, 0 );

if ( INVALID_SOCKET ==  sock)
{
  AfxMessageBox("Error:  Broadcast DoUdp - INVALID_SOCKET");
}

int iTimeoutLen = 10;
err = setsockopt(sock,                   SOL_SOCKET,
                               SO_LINGER,
                               (CHAR *) &iTimeoutLen,sizeof(int));




Moth
0
Moth
Asked:
Moth
1 Solution
 
IexpertCommented:
timeval timeout;
timeout.tv_sec =8; //seconds
timeout.tv_usec = 0; //micro seconds

int nfound = select(FD_SETSIZE, &readmask, (fd_set*) NULL, (fd_set*) NULL, &timeout)

if (nfound < 0)
      printf("Select error [%d]",WSAGetLastError());
else if (nfound==0)
      //deal with timeout here
else
      //read or accept() socket
0
 
MaydipalleCommented:
Hi,
 Create the system structure of type LINGER and set proper values as described below.LINGER as defined as
struct linger {
    u_short    l_onoff;
    u_short    l_linger;
}

To enable SO_LINGER, the application should set l_onoff to a nonzero value, set l_linger to zero or the desired time-out (in seconds), and call setsockopt. To enable SO_DONTLINGER (that is, disable SO_LINGER) l_onoff should be set to zero and setsockopt should be called. Note that enabling SO_LINGER with a nonzero time-out on a nonblocking socket is not recommended.
Enabling SO_LINGER also disables SO_DONTLINGER, and vice versa. Note that if SO_DONTLINGER is DISABLED (that is, SO_LINGER is ENABLED) then no time-out value is specified. In this case, the time-out used is implementation dependent. If a previous time-out has been established for a socket (by enabling SO_LINGER), then this time-out value should be reinstated by the service provider.Supply this structure instead of SO_LINGER in your application

Hope this may help you.Just I got this from some where in the documentation

Madhav
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now