Question

Network, closing socket... timewait.

Asked by: navigator

Ok, I have a tinsy problem.

I am trying to interact with an existing server (I have NO CONTROL over the server)  it is a temporary tcp stream connection, only meant to send and receive a single command (think of it like a web server, but it isn't)

Now, I need to get an update from this server once every second (sometimes even more frequently).

My problem is, this is what is showing up in my netstat...

tcp        0      0 localhost.localdo:34373 localhost.localdo:20000 TIME_WAIT
tcp        0      0 localhost.localdo:34372 localhost.localdo:20000 TIME_WAIT
tcp        0      0 localhost.localdo:34375 localhost.localdo:20000 TIME_WAIT
tcp        0      0 localhost.localdo:34374 localhost.localdo:20000 TIME_WAIT
tcp        0      0 localhost.localdo:34369 localhost.localdo:20000 TIME_WAIT

And this goes on and on and on.

I am closing my end of the connection, and I'm fairly sure the server is closing its end of the connection.  What can I do to prevent this time wait issue?

Here is the meat of the section of code that might be causing the problem.

I am sending the request.  I am then waiting for a response (up to a certain period) (check sock does a select to see if there is data to be read) then I am returning the results.

do {
                Invalid = CheckSocket(sock);
                Counter++;
        } while ((Counter<5) && (Invalid == 1));

        if (Invalid)
                sprintf(IBuffer,"Server is Busy, please try again later.\n");
        else
        if (read(sock, IBuffer,( sizeof(unsigned char)*FEEDBACK_BUFFER_LENGTH))
< 0) {
                perror("receiveing on stream socket");
                close(sock);
                exit(1);
        }

        //*********************************************************************
        //      Close this connection, since the stream isn't persistent
        //*********************************************************************
        close(sock);

Now, my program is operating normally, but those TIME_WAIT's are stacking up.  is there any way to not have those happen, or to reduce the length of time of the wait so it won't stack up so fast?

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2002-05-15 at 21:22:25ID20301160
Tags

socket

,

time_wait

,

timewait

Topic

C Programming Language

Participating Experts
2
Points
100
Comments
8

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. netstat -a
    What does the output from netstat -a command mean on unix. Usually it says LISTEN, ESTABLISHED. But what does TIME_WAIT mean, is there a good reference to these messages?
  2. Sockets
    I am using Winsock 2 on a Windows NT platform. I have two applications listening on the same port for UDP packets. It seems like only one of them can get the data at a time. Shouldn't this data be copied to all listening sockets? I have looked at some reference material w...
  3. netstat
    1. What is the meaning of each entry of the below? C:\WINDOWS\COMMAND>netstat Active Connections Proto Local Address Foreign Address State TCP a4p9s7:1028 localhost.ccs.yorku.ca:135 ESTABLISHED TCP a4p9s7:135 localhost.ccs.yorku.ca:1028 ESTABLISHED ...
  4. Sizeof()
    if 'char *array' points to an array in dynamic memory, how can i find the size of the array? i know sizeof() doesnt work in this situation...
  5. socket programming
    I have a C program that runs on Linux. It captures, reads and prints out the data of ICMP echo request packets going through the machine it’s running on. I’m able to capture ICMP ECHO request packets but I don’t know why for every single ICMP echo request packet, I capture i...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: navigatorPosted on 2002-05-15 at 21:51:20ID: 7012930

btw - I know the TIME_WAIT state is normal, my problem is that they are piling up too fast.  I have NO control over the server I am querying, so there is no way for me to change it from a temporary stream to a long term stream.

Basically, what I am asking, is there anything I can do on the client end to reduce or remove the TIME_WAIT?  I've tested it with 5 clients hitting the server at the average 1.5 second interval, and the system resources are dwindling fast.

 

by: sevaPosted on 2002-05-15 at 23:38:19ID: 7013049

This is what Rich Stevens says about TIME_WAIT:

"There are two reasons for the TIME_WAIT state:
1. to implement TCP's full-duplex connection termination  
   reliably
2. to allow old duplicate segments to expire in the network
"
That means, we have to accept going through this state
of a TCP connection. Otherwise, it may not work correctly.

The duration of TIME_WAIT state is implementation-dependent (recommended value is 4 minutes, BSD has 1 minute).

 

by: cincin77Posted on 2002-05-16 at 02:24:45ID: 7013278

http://www.faqs.org/faqs/unix-faq/socket/


2.7.  Please explain the TIME_WAIT state.

  Remember that TCP guarantees all data transmitted will be delivered,
  if at all possible.  When you close a socket, the server goes into a
  TIME_WAIT state, just to be really really sure that all the data has
  gone through.  When a socket is closed, both sides agree by sending
  messages to each other that they will send no more data.  This, it
  seemed to me was good enough, and after the handshaking is done, the
  socket should be closed.  The problem is two-fold.  First, there is no
  way to be sure that the last ack was communicated successfully.
  Second, there may be "wandering duplicates" left on the net that must
  be dealt with if they are delivered.

  Andrew Gierth (andrew@erlenstar.demon.co.uk) helped to explain the
  closing sequence in the following usenet posting:

  Assume that a connection is in ESTABLISHED state, and the client is
  about to do an orderly release. The client's sequence no. is Sc, and
  the server's is Ss. The pipe is empty in both directions.

          Client                                                   Server
          ======                                                   ======
          ESTABLISHED                                              ESTABLISHED
          (client closes)
          ESTABLISHED                                              ESTABLISHED
                       <CTL=FIN+ACK><SEQ=Sc><ACK=Ss> ------->>
          FIN_WAIT_1
                       <<-------- <CTL=ACK><SEQ=Ss><ACK=Sc+1>
          FIN_WAIT_2                                               CLOSE_WAIT
                       <<-------- <CTL=FIN+ACK><SEQ=Ss><ACK=Sc+1>  (server closes)
                                                                   LAST_ACK
                       <CTL=ACK>,<SEQ=Sc+1><ACK=Ss+1> ------->>
          TIME_WAIT                                                CLOSED
          (2*msl elapses...)
          CLOSED

  Note: the +1 on the sequence numbers is because the FIN counts as one
  byte of data. (The above diagram is equivalent to fig. 13 from RFC
  793).

  Now consider what happens if the last of those packets is dropped in
  the network. The client has done with the connection; it has no more
  data or control info to send, and never will have. But the server does
  not know whether the client received all the data correctly; that's
  what the last ACK segment is for. Now the server may or may not care
  whether the client got the data, but that is not an issue for TCP; TCP
  is a reliable rotocol, and must distinguish between an orderly
  connection close where all data is transferred, and a connection abort
  where data may or may not have been lost.

  So, if that last packet is dropped, the server will retransmit it (it
  is, after all, an unacknowledged segment) and will expect to see a
  suitable ACK segment in reply.  If the client went straight to CLOSED,
  the only possible response to that retransmit would be a RST, which
  would indicate to the server that data had been lost, when in fact it
  had not been.

  (Bear in mind that the server's FIN segment may, additionally, contain
  data.)

  DISCLAIMER: This is my interpretation of the RFCs (I have read all the
  TCP-related ones I could find), but I have not attempted to examine
  implementation source code or trace actual connections in order to
  verify it. I am satisfied that the logic is correct, though.

  More commentarty from Vic:

  The second issue was addressed by Richard Stevens (rstevens@noao.edu,
  author of "Unix Network Programming", see ``1.5 Where can I get source
  code for the book [book  title]?'').  I have put together quotes from
  some of his postings and email which explain this.  I have brought
  together paragraphs from different postings, and have made as few
  changes as possible.

  From Richard Stevens (rstevens@noao.edu):

  If the duration of the TIME_WAIT state were just to handle TCP's full-
  duplex close, then the time would be much smaller, and it would be
  some function of the current RTO (retransmission timeout), not the MSL
  (the packet lifetime).

  A couple of points about the TIME_WAIT state.

  o  The end that sends the first FIN goes into the TIME_WAIT state,
     because that is the end that sends the final ACK.  If the other
     end's FIN is lost, or if the final ACK is lost, having the end that
     sends the first FIN maintain state about the connection guarantees
     that it has enough information to retransmit the final ACK.

  o  Realize that TCP sequence numbers wrap around after 2**32 bytes
     have been transferred.  Assume a connection between A.1500 (host A,
     port 1500) and B.2000.  During the connection one segment is lost
     and retransmitted.  But the segment is not really lost, it is held
     by some intermediate router and then re-injected into the network.
     (This is called a "wandering duplicate".)  But in the time between
     the packet being lost & retransmitted, and then reappearing, the
     connection is closed (without any problems) and then another
     connection is established between the same host, same port (that
     is, A.1500 and B.2000; this is called another "incarnation" of the
     connection).  But the sequence numbers chosen for the new
     incarnation just happen to overlap with the sequence number of the
     wandering duplicate that is about to reappear.  (This is indeed
     possible, given the way sequence numbers are chosen for TCP
     connections.)  Bingo, you are about to deliver the data from the
     wandering duplicate (the previous incarnation of the connection) to
     the new incarnation of the connection.  To avoid this, you do not
     allow the same incarnation of the connection to be reestablished
     until the TIME_WAIT state terminates.

     Even the TIME_WAIT state doesn't complete solve the second problem,
     given what is called TIME_WAIT assassination.  RFC 1337 has more
     details.

  o  The reason that the duration of the TIME_WAIT state is 2*MSL is
     that the maximum amount of time a packet can wander around a
     network is assumed to be MSL seconds.  The factor of 2 is for the
     round-trip.  The recommended value for MSL is 120 seconds, but
     Berkeley-derived implementations normally use 30 seconds instead.
     This means a TIME_WAIT delay between 1 and 4 minutes.  Solaris 2.x
     does indeed use the recommended MSL of 120 seconds.

  A wandering duplicate is a packet that appeared to be lost and was
  retransmitted.  But it wasn't really lost ... some router had
  problems, held on to the packet for a while (order of seconds, could
  be a minute if the TTL is large enough) and then re-injects the packet
  back into the network.  But by the time it reappears, the application
  that sent it originally has already retransmitted the data contained
  in that packet.

  Because of these potential problems with TIME_WAIT assassinations, one
  should not avoid the TIME_WAIT state by setting the SO_LINGER option
  to send an RST instead of the normal TCP connection termination
  (FIN/ACK/FIN/ACK).  The TIME_WAIT state is there for a reason; it's
  your friend and it's there to help you :-)

  I have a long discussion of just this topic in my just-released
  "TCP/IP Illustrated, Volume 3".  The TIME_WAIT state is indeed, one of
  the most misunderstood features of TCP.

  I'm currently rewriting "Unix Network Programming" (see ``1.5 Where
  can I get source code for the book [book  title]?''). and will include
  lots more on this topic, as it is often confusing and misunderstood.

  An additional note from Andrew:

  Closing a socket: if SO_LINGER has not been called on a socket, then
  close() is not supposed to discard data. This is true on SVR4.2 (and,
  apparently, on all non-SVR4 systems) but apparently not on SVR4; the
  use of either shutdown() or SO_LINGER seems to be required to
  guarantee delivery of all data.

 

by: navigatorPosted on 2002-05-16 at 05:21:56ID: 7013523

I had read both of those things on the net, I was just hoping there was a way.  I have found ways to reduce the length of time by recompiling the kernel, but that would only work for me, and isn't  a valid option for everyone.

Personally, if it were me, I'd make it a long term socket.  Right now, you connect, send you request, and get a reply that is no more then about 2040, but most reponses are in the range of 50 bytes.

I am currently begging the author of the server to convert the program to a long term stream or UDP (I don't think delivery guarantee is vital for this app to be honest, but if it is, making the stream long term would be a better way to go.  testing with 5 clients hitting the server for data every 1.5 seconds is piling up >140 TIME_WAITs, which may not be a lot, but this is only 5 clients, with 1 request; by the time it is done, that 1 request could really be 3 to 5 requests in that span of time - each request requiring a new connection to the server piling up the TIME_WAITs even higher, if there were 50 clients making 5 requests, I figure that could pile up to 35000 TIME_WAIT's, and that just seems a waste for what the server is doing)

 

by: sevaPosted on 2002-05-16 at 10:34:24ID: 7014366

Well, it seems to me that there is a way (again,
according to Stevens).
If you set SO_LINGER option using the struct linger
{
  int l_onoff;
  int l_linger;
}
where l_onoff set to nonzero and l_linger is zero,
"TCP aborts the connection when it is closed.
 That is, TCP discards any data still remaining in the
 socket send buffer and sends an RST to the peer, not
 the normal four-packet connection termination
 sequence... This avoids TCP TIME_WAIT state...
 Some implementations, notably Solaris 2.x where x <= 5,
 do not implement this feature of SO_LINGER"

 

by: navigatorPosted on 2002-05-16 at 14:27:20ID: 7014961

Do you know if this can be done on the client, or is it a server implementation only, or both?

 

by: sevaPosted on 2002-05-16 at 16:45:25ID: 7015224

I believe this can be done on both.
I think there is no real distinction between the server and the client after a connection is established.

Either one can close the connection, so it will send
RST and avoid TIME_WAIT.

 

by: navigatorPosted on 2002-05-16 at 18:55:15ID: 7015368

Works for me, thanks for the added info.  I'm still trying to get the programmer to re-code his server, I think I'm making progress ;)  I'd rather have the server recoded then disable the time_wait...

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...