Implementing timeouts with TCP sockets

This is a discussion on Implementing timeouts with TCP sockets within the C Programming forums, part of the General Programming Boards category; Hi, Sorry, if this thread doesnt fit here. I will still ask. I want to wait for a certain timeout ...

  1. #1
    Registered User
    Join Date
    Apr 2005
    Posts
    134

    Implementing timeouts with TCP sockets

    Hi,

    Sorry, if this thread doesnt fit here. I will still ask.

    I want to wait for a certain timeout value (60 secs) after sending a request packet over a TCP socket, before deciding if the peer is dead or alive. If the reply packet comes within 60 secs from starting timer, I need to stop the timer and proceed further.

    How can I implement this functionality with TCP recv() function? Any pointers ?

    Thanks,

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Consider looking at select. Make a time stamp for each connection. Call select in a loop every so often. If that function isn't ready for reading or writing (depending on what you're doing) by the time your time runs out, close the connection. There's probably a better way to do it, but that should work.

    Also consider searching for Beej's guide to sockets.

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Apr 2005
    Posts
    134
    Hi quzah,

    I wanted to check the timeout during connect() as well as send()/recv() state. I googled for it and found a way to do it using setsockopt(). Following was my solution.

    Code:
    struct timeval tv;
    
    tv.tv_sec = 30;       /* Timeout in seconds */
    
    setsockopt(sockid, SOL_SOCKET, SO_SNDTIMEO,(struct timeval *)&tv,sizeof(struct timeval));
    setsockopt(sockid, SOL_SOCKET, SO_RCVTIMEO,(struct timeval *)&tv,sizeof(struct timeval));
    It worked just fine.

    Thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. TCP Header problem (error)
    By nasim751 in forum C Programming
    Replies: 1
    Last Post: 04-25-2008, 07:30 AM
  2. TCP Sockets: multiple clients - one server
    By Printisor in forum C Programming
    Replies: 4
    Last Post: 11-01-2007, 10:34 AM
  3. TCP sockets classes
    By Camel in forum Linux Programming
    Replies: 5
    Last Post: 12-17-2006, 06:29 PM
  4. Accessing TCP flags in TCP packets on Linux using C !!
    By vishamr in forum Linux Programming
    Replies: 2
    Last Post: 10-16-2006, 08:48 AM
  5. Can TCP sockets also receive ICMP...?
    By failure_to in forum Networking/Device Communication
    Replies: 3
    Last Post: 06-09-2004, 10:36 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21