home *** CD-ROM | disk | FTP | other *** search
/ Internet Info 1997 December / Internet_Info_CD-ROM_Walnut_Creek_December_1997.iso / faqs / comp / answers / unix-faq / socket < prev   
Encoding:
Text File  |  1997-09-30  |  87.8 KB  |  2,033 lines

  1. Newsgroups: comp.unix.programmer,comp.unix.answers,comp.answers,news.answers
  2. Path: senator-bedfellow.mit.edu!bloom-beacon.mit.edu!grapevine.lcs.mit.edu!newsswitch.lcs.mit.edu!netnews.com!howland.erols.net!newsfeed.direct.ca!hub.org!news.trends.ca!innuendo.tlug.org!brutus!vic
  3. From: vic@brutus.tlug.org (Vic Metcalfe)
  4. Subject: [comp.unix.programmer] Unix-socket-faq for network programming
  5. Approved: news-answers-request@MIT.EDU
  6. Followup-To: comp.unix.programmer
  7. X-Newsreader: TIN [version 1.2 PL2]
  8. Organization: Zymurgy Systems, Aurora, Ontario, Canada
  9. Message-ID: <1997Sep22.232040.1262@brutus.tlug.org>
  10. Date: Mon, 22 Sep 1997 23:20:40 GMT
  11. Summary: This posting offers answers to frequent questions about network
  12.          programming in the unix environment using sockets.
  13. Lines: 2017
  14. Xref: senator-bedfellow.mit.edu comp.unix.programmer:65156 comp.answers:28266 news.answers:113390
  15.  
  16. Archive-name: unix-faq/socket
  17. Posting-Frequency: monthly
  18. Last-modified: 1997/04/22
  19. URL: http://www.auroraonline.com/sock-faq/
  20.  
  21.   Programming UNIX Sockets in C - Frequently Asked Questions
  22.   Created by Vic Metcalfe, Andrew Gierth and other contributers
  23.   April 22, 1997
  24.  
  25.   This is a list of frequently asked questions, with answers about pro-
  26.   gramming TCP/IP applications in unix with the sockets interface.
  27.   ______________________________________________________________________
  28.  
  29.   Table of Contents:
  30.  
  31.   1.      General Information and Concepts
  32.  
  33.   1.1.    About this FAQ
  34.  
  35.   1.2.    Who is this FAQ for?
  36.  
  37.   1.3.    What are Sockets?
  38.  
  39.   1.4.    How do Sockets Work?
  40.  
  41.   1.5.    Where can I get source code for the book [book title]?
  42.  
  43.   1.6.    Where can I get more information?
  44.  
  45.   2.      Questions regarding both Clients and Servers (TCP/SOCK_STREAM)
  46.  
  47.   2.1.    How can I tell when a socket is closed on the other end?
  48.  
  49.   2.2.    What's with the second parameter in bind()?
  50.  
  51.   2.3.    How do I get the port number for a given service?
  52.  
  53.   2.4.    If bind() fails, what should I do with the socket descriptor?
  54.  
  55.   2.5.    How do I properly close a socket?
  56.  
  57.   2.6.    When should I use shutdown()?
  58.  
  59.   2.7.    Please explain the TIME_WAIT state.
  60.  
  61.   2.8.    Why does it take so long to detect that the peer died?
  62.  
  63.   2.9.    What are the pros/cons of select(), non-blocking I/O and
  64.   SIGIO?
  65.  
  66.   2.10.   Why do I get EPROTO from read()?
  67.  
  68.   2.11.   How can I force a socket to send the data in it's buffer?
  69.  
  70.   2.12.   Where can a get a library for programming sockets?
  71.  
  72.   2.13.   How come select says there is data, but read returns zero?
  73.  
  74.   2.14.   Whats the difference between select() and poll()?
  75.  
  76.   2.15.   How do I send [this] over a socket?
  77.  
  78.   2.16.   How do I use TCP_NODELAY?
  79.  
  80.   2.17.   What exactly does the Nagle algorithm do?
  81.  
  82.   2.18.   What is the difference between read() and recv()?
  83.  
  84.   2.19.   I see that send()/write() can generate SIGPIPE. Is there any
  85.   advantage to handling the signal, rather than just ignoring it and
  86.   checking for the EPIPE error? Are there any useful parameters passed
  87.   to the signal catching function?
  88.  
  89.   2.20.   After the chroot(), calls to socket() are failing.  Why?
  90.  
  91.   2.21.   Why do I keep getting EINTR from the socket calls?
  92.  
  93.   2.22.   When will my application receive SIGPIPE?
  94.  
  95.   2.23.   What are socket exceptions?  What is out-of-band data?
  96.  
  97.   2.24.   How can I find the full hostname (FQDN) of the system I'm
  98.   running on?
  99.  
  100.   2.25.   How would I put my socket in non-blocking mode?
  101.  
  102.   3.      Writing Client Applications (TCP/SOCK_STREAM)
  103.  
  104.   3.1.    How do I convert a string into an internet address?
  105.  
  106.   3.2.    How can my client work through a firewall/proxy server?
  107.  
  108.   3.3.    Why does connect() succeed even before my server did an
  109.   accept()?
  110.  
  111.   3.4.    Why do I sometimes loose a server's address when using more
  112.   than one server?
  113.  
  114.   3.5.    How can I set the timeout for the connect() system call?
  115.  
  116.   3.6.    Should I bind() a port number in my client program, or let the
  117.   system choose one for me on the connect() call?
  118.  
  119.   3.7.    Why do I get "connection refused" when the server isn't
  120.   running?
  121.  
  122.   3.8.    What does one do when one does not know how much information
  123.   is comming over the socket ? Is there a way to have a dynamic buffer ?
  124.  
  125.   4.      Writing Server Applications (TCP/SOCK_STREAM)
  126.  
  127.   4.1.    How come I get "address already in use" from bind()?
  128.  
  129.   4.2.    Why don't my sockets close?
  130.  
  131.   4.3.    How can I make my server a daemon?
  132.  
  133.   4.4.    How can I listen on more than one port at a time?
  134.  
  135.   4.5.    What exactly does SO_REUSEADDR do?
  136.  
  137.   4.6.    What exactly does SO_LINGER do?
  138.  
  139.   4.7.    What exactly does SO_KEEPALIVE do?
  140.  
  141.   4.8.    How can I bind() to a port number < 1024?
  142.  
  143.   4.9.    How do I get my server to find out the client's address /
  144.   hostname?
  145.  
  146.   4.10.   How should I choose a port number for my server?
  147.  
  148.   4.11.   What is the difference between SO_REUSEADDR and SO_REUSEPORT?
  149.  
  150.   4.12.   How can I write a multi-homed server?
  151.  
  152.   4.13.   How can I read only one character at a time?
  153.  
  154.   4.14.   I'm trying to exec() a program from my server, and attach my
  155.   socket's IO to it, but I'm not getting all the data across.  Why?
  156.  
  157.   5.      Writing UDP/SOCK_DGRAM applications
  158.  
  159.   5.1.    When should I use UDP instead of TCP?
  160.  
  161.   5.2.    What is the difference between "connected" and "unconnected"
  162.   sockets?
  163.  
  164.   5.3.    Does doing a connect() call affect the receive behaviour of
  165.   the socket?
  166.  
  167.   5.4.    How can I read ICMP errors from "connected" UDP sockets?
  168.  
  169.   5.5.    How can I be sure that a UDP message is received?
  170.  
  171.   5.6.    How can I be sure that UDP messages are received in order?
  172.  
  173.   5.7.    How often should I re-transmit un-acknowleged messages?
  174.  
  175.   5.8.    How come only the first part of my datagram is getting
  176.   through?
  177.  
  178.   5.9.    Why does the socket's buffer fill up sooner than expected?
  179.  
  180.   6.      Sample Source Code
  181.   ______________________________________________________________________
  182.  
  183.   1.  General Information and Concepts
  184.  
  185.   1.1.  About this FAQ
  186.  
  187.   This FAQ is maintained by Vic Metcalfe (vic@acm.org), with lots of
  188.   assistance from Andrew Gierth (andrew@erlenstar.demon.co.uk).  I am
  189.   depending on the true wizards to fill in the details, and correct my
  190.   (no doubt) plentiful mistakes.  The code examples in this FAQ are
  191.   written to be easy to follow and understand.  It is up to the reader
  192.   to make them as efficient as required.  I started this faq because
  193.   after reading comp.unix.programmer for a short time, it became evident
  194.   that a FAQ was needed.
  195.  
  196.   The FAQ is available at the following locations:
  197.  
  198.      Usenet: (Posted on the 21st of each month)
  199.         news.answers, comp.answers, comp.unix.answers,
  200.         comp.unix.programmer
  201.  
  202.      FTP:
  203.         ftp://rtfm.mit.edu/pub/usenet/news.answers/unix-faq/socket
  204.  
  205.      WWW:
  206.         http://www.auroraonline.com/sock-faq
  207.         http://kipper.york.ac.uk/~vic/sock-faq
  208.  
  209.   Please email me if you would like to correct or clarify an answer.  I
  210.   would also like to hear from you if you would like me to add a
  211.   question to the list.  I may not be able to answer it, but I can add
  212.   it in the hopes that someone else will submit an answer.  Every hour I
  213.   seem to be getting even busier, so if I am slow to respond to your
  214.   email, please be patient.  If more than a week passes you may want to
  215.   send me another one as I often put messages aside for later and then
  216.   forget about them.  I'll have to work on dealing with my mail better,
  217.   but until then feel free to pester me a little bit.
  218.  
  219.   1.2.  Who is this FAQ for?
  220.  
  221.   This FAQ is for C programmers in the Unix environment.  It is not
  222.   intended for WinSock programmers, or for Perl, Java, etc.  I have
  223.   nothing against Windows or Perl, but I had to limit the scope of the
  224.   FAQ for the first draft.  In the future, I would really like to
  225.   provide examples for Perl, Java, and maybe others.  For now though I
  226.   will concentrate on correctness and completeness for C.
  227.  
  228.   This version of the FAQ will only cover sockets of the AF_INET family,
  229.   since this is their most common use.  Coverage of other types of
  230.   sockets may be added later.
  231.  
  232.   1.3.  What are Sockets?
  233.  
  234.   Sockets are just like "worm holes" in science fiction.  When things go
  235.   into one end, they (should) come out of the other.  Different kinds of
  236.   sockets have different properties.  Sockets are either connection-
  237.   oriented or connectionless.  Connection-oriented sockets allow for
  238.   data to flow back and forth as needed, while connectionless sockets
  239.   (also known as datagram sockets) allow only one message at a time to
  240.   be transmitted, without an open connection.  There are also different
  241.   socket families.  The two most common are AF_INET for internet
  242.   connections, and AF_UNIX for unix IPC (interprocess communication).
  243.   As stated earlier, this FAQ deals only with AF_INET sockets.
  244.  
  245.   1.4.  How do Sockets Work?
  246.  
  247.   The implementation is left up to the vendor of your particular unix,
  248.   but from the point of view of the programmer, connection-oriented
  249.   sockets work a lot like files, or pipes.  The most noticeable
  250.   difference, once you have your file descriptor is that read() or
  251.   write() calls may actually read or write fewer bytes than requested.
  252.   If this happens, then you will have to make a second call for the rest
  253.   of the data.  There are examples of this in the source code that
  254.   accompanies the faq.
  255.  
  256.   1.5.  Where can I get source code for the book [book title]?
  257.  
  258.   Here is a list of the places I know to get source code for network
  259.   programming books.  It is very short, so please mail me with any
  260.   others you know of.
  261.  
  262.   Title: Unix Network Programming
  263.   Author: W. Richard Stevens (rstevens@noao.edu)
  264.   Publisher: Prentice Hall, Inc.
  265.   ISBN: 0-13-949876-1
  266.   URL: http://www.noao.edu/~rstevens
  267.  
  268.   Title: Power Programming with RPC
  269.   Author: John Bloomer
  270.   Publisher: O'Reilly & Associates, Inc.
  271.   ISBN: 0-937175-77-3
  272.   URL: ftp://ftp.uu.net/published/oreilly/nutshell/rpc/rpc.tar.Z
  273.  
  274.   Recommended by: Lokmanm Merican (lokmanm#pop4.jaring.my@199.1.1.88)
  275.   Title: UNIX PROGRAM DEVELOPMENT for IBM PC'S Including OSF/Motif
  276.   Author: Thomas Yager
  277.   Publisher: Addison Wesley, 1991
  278.   ISBN: 0-201-57727-5
  279.  
  280.   1.6.  Where can I get more information?
  281.  
  282.   I keep a copy of the resources I know of on my socks page on the web.
  283.   I don't remember where I got most of these items, but some day I'll
  284.   check out their sources, and provide ftp information here.  For now,
  285.   you can get them at http://www.auroraonline.com/sock-faq.
  286.  
  287.   There is a good TCP/IP FAQ maintained by George Neville-Neil
  288.   (gnn@wrs.com) which can be found at
  289.   http://www.visi.com/~khayes/tcpipfaq.html
  290.  
  291.   2.  Questions regarding both Clients and Servers (TCP/SOCK_STREAM)
  292.  
  293.   2.1.  How can I tell when a socket is closed on the other end?
  294.  
  295.   From Andrew Gierth (andrew@erlenstar.demon.co.uk):
  296.  
  297.   AFAIK:
  298.  
  299.   If the peer calls close() or exits, without having messed with
  300.   SO_LINGER, then our calls to read() should return 0. It is less clear
  301.   what happens to write() calls in this case; I would expect EPIPE, not
  302.   on the next call, but the one after.
  303.  
  304.   If the peer reboots, or sets l_onoff = 1, l_linger = 0 and then
  305.   closes, then we should get ECONNRESET (eventually) from read(), or
  306.   EPIPE from write().
  307.  
  308.   I should also point out that when write() returns EPIPE, it also
  309.   raises the SIGPIPE signal - you never see the EPIPE error unless you
  310.   handle or ignore the signal.
  311.  
  312.   If the peer remains unreachable, we should get some other error.
  313.  
  314.   I don't think that write() can legitimately return 0.  read() should
  315.   return 0 on receipt of a FIN from the peer, and on all following
  316.   calls.
  317.  
  318.   So yes, you must expect read() to return 0.
  319.  
  320.   As an example, suppose you are receiving a file down a TCP link; you
  321.   might handle the return from read() like this:
  322.  
  323.   rc = read(sock,buf,sizeof(buf));
  324.   if (rc > 0)
  325.   {
  326.       write(file,buf,rc);
  327.       /* error checking on file omitted */
  328.   }
  329.   else if (rc == 0)
  330.   {
  331.       close(file);
  332.       close(sock);
  333.       /* file received successfully */
  334.   }
  335.   else /* rc < 0 */
  336.   {
  337.       /* close file and delete it, since data is not complete
  338.          report error, or whatever */
  339.   }
  340.  
  341.   2.2.  What's with the second parameter in bind()?
  342.  
  343.   The man page shows it as "struct sockaddr *my_addr".  The sockaddr
  344.   struct though is just a place holder for the structure it really
  345.   wants.  You have to pass different structures depending on what kind
  346.   of socket you have.  For an AF_INET socket, you need the sockaddr_in
  347.   structure.  It has three fields of interest:
  348.  
  349.      sin_family
  350.         Set this to AF_INET.
  351.  
  352.      sin_port
  353.         The network byte-ordered 16 bit port number
  354.  
  355.      sin_addr
  356.         The host's ip number.  This is a struct in_addr, which contains
  357.         only one field, s_addr which is a u_long.
  358.  
  359.   2.3.  How do I get the port number for a given service?
  360.  
  361.   Use the getservbyname() routine.  This will return a pointer to a
  362.   servent structure.  You are interested in the s_port field, which
  363.   contains the port number, with correct byte ordering (so you don't
  364.   need to call htons() on it).  Here is a sample routine:
  365.  
  366.   /* Take a service name, and a service type, and return a port number.  If the
  367.      service name is not found, it tries it as a decimal number.  The number
  368.      returned is byte ordered for the network. */
  369.   int atoport(char *service, char *proto) {
  370.     int port;
  371.     long int lport;
  372.     struct servent *serv;
  373.     char *errpos;
  374.  
  375.     /* First try to read it from /etc/services */
  376.     serv = getservbyname(service, proto);
  377.     if (serv != NULL)
  378.       port = serv->s_port;
  379.     else { /* Not in services, maybe a number? */
  380.       lport = strtol(service,&errpos,0);
  381.       if ( (errpos[0] != 0) || (lport < 1) || (lport > 5000) )
  382.         return -1; /* Invalid port address */
  383.       port = htons(lport);
  384.     }
  385.     return port;
  386.   }
  387.  
  388.   2.4.  If bind() fails, what should I do with the socket descriptor?
  389.  
  390.   If you are exiting, I have been assured by Andrew that all unixes will
  391.   close open file descriptors on exit.  If you are not exiting though,
  392.   you can just close it with a regular close() call.
  393.  
  394.   2.5.  How do I properly close a socket?
  395.  
  396.   This question is usually asked by people who try close(), because they
  397.   have seen that that is what they are supposed to do, and then run
  398.   netstat and see that their socket is still active.  Yes, close() is
  399.   the correct method.  To read about the TIME_WAIT state, and why it is
  400.   important, refer to ``2.7 Please explain the TIME_WAIT state.''.
  401.  
  402.   2.6.  When should I use shutdown()?
  403.  
  404.   From Michael Hunter (mphunter@qnx.com):
  405.  
  406.   shutdown() is useful for deliniating when you are done providing a
  407.   request to a server using TCP.  A typical use is to send a request to
  408.   a server followed by a shutdown().  The server will read your request
  409.   followed by an EOF (read of 0 on most unix implementations).  This
  410.   tells the server that it has your full request.  You then go read
  411.   blocked on the socket.  The server will process your request and send
  412.   the necessary data back to you followed by a close.  When you have
  413.   finished reading all of the response to your request you will read an
  414.   EOF thus signifying that you have the whole response.  It should be
  415.   noted the TTCP (TCP for Transactions -- see R. Steven's home page)
  416.   provides for a better method of tcp transaction management.
  417.  
  418.   2.7.  Please explain the TIME_WAIT state.
  419.  
  420.   Remember that TCP guarantees all data transmitted will be delivered,
  421.   if at all possible.  When you close a socket, the server goes into a
  422.   TIME_WAIT state, just to be really really sure that all the data has
  423.   gone through.  When a socket is closed, both sides agree by sending
  424.   messages to each other that they will send no more data.  This, it
  425.   seemed to me was good enough, and after the handshaking is done, the
  426.   socket should be closed.  The problem is two-fold.  First, there is no
  427.   way to be sure that the last ack was communicated successfully.
  428.   Second, there may be "wandering duplicates" left on the net that must
  429.   be dealt with if they are delivered.
  430.  
  431.   Andrew Gierth (andrew@erlenstar.demon.co.uk) helped to explain the
  432.   closing sequence in the following usenet posting:
  433.  
  434.   Assume that a connection is in ESTABLISHED state, and the client is
  435.   about to do an orderly release. The client's sequence no. is Sc, and
  436.   the server's is Ss. The pipe is empty in both directions.
  437.  
  438.           Client                                                   Server
  439.           ======                                                   ======
  440.           ESTABLISHED                                              ESTABLISHED
  441.           (client closes)
  442.           ESTABLISHED                                              ESTABLISHED
  443.                        <CTL=FIN+ACK><SEQ=Sc><ACK=Ss> ------->>
  444.           FIN_WAIT_1
  445.                        <<-------- <CTL=ACK><SEQ=Ss><ACK=Sc+1>
  446.           FIN_WAIT_2                                               CLOSE_WAIT
  447.                        <<-------- <CTL=FIN+ACK><SEQ=Ss><ACK=Sc+1>  (server closes)
  448.                                                                    LAST_ACK
  449.                        <CTL=ACK>,<SEQ=Sc+1><ACK=Ss+1> ------->>
  450.           TIME_WAIT                                                CLOSED
  451.           (2*msl elapses...)
  452.           CLOSED
  453.  
  454.   Note: the +1 on the sequence numbers is because the FIN counts as one
  455.   byte of data. (The above diagram is equivalent to fig. 13 from RFC
  456.   793).
  457.  
  458.   Now consider what happens if the last of those packets is dropped in
  459.   the network. The client has done with the connection; it has no more
  460.   data or control info to send, and never will have. But the server does
  461.   not know whether the client received all the data correctly; that's
  462.   what the last ACK segment is for. Now the server may or may not care
  463.   whether the client got the data, but that is not an issue for TCP; TCP
  464.   is a reliable rotocol, and must distinguish between an orderly
  465.   connection close where all data is transferred, and a connection abort
  466.   where data may or may not have been lost.
  467.  
  468.   So, if that last packet is dropped, the server will retransmit it (it
  469.   is, after all, an unacknowledged segment) and will expect to see a
  470.   suitable ACK segment in reply.  If the client went straight to CLOSED,
  471.   the only possible response to that retransmit would be a RST, which
  472.   would indicate to the server that data had been lost, when in fact it
  473.   had not been.
  474.  
  475.   (Bear in mind that the server's FIN segment may, additionally, contain
  476.   data.)
  477.  
  478.   DISCLAIMER: This is my interpretation of the RFCs (I have read all the
  479.   TCP-related ones I could find), but I have not attempted to examine
  480.   implementation source code or trace actual connections in order to
  481.   verify it. I am satisfied that the logic is correct, though.
  482.  
  483.   More commentarty from Vic:
  484.  
  485.   The second issue was addressed by Richard Stevens (rstevens@noao.edu,
  486.   author of "Unix Network Programming", see ``1.5 Where can I get source
  487.   code for the book [book  title]?'').  I have put together quotes from
  488.   some of his postings and email which explain this.  I have brought
  489.   together paragraphs from different postings, and have made as few
  490.   changes as possible.
  491.  
  492.   From Richard Stevens (rstevens@noao.edu):
  493.  
  494.   If the duration of the TIME_WAIT state were just to handle TCP's full-
  495.   duplex close, then the time would be much smaller, and it would be
  496.   some function of the current RTO (retransmission timeout), not the MSL
  497.   (the packet lifetime).
  498.  
  499.   A couple of points about the TIME_WAIT state.
  500.  
  501.   o  The end that sends the first FIN goes into the TIME_WAIT state,
  502.      because that is the end that sends the final ACK.  If the other
  503.      end's FIN is lost, or if the final ACK is lost, having the end that
  504.      sends the first FIN maintain state about the connection guarantees
  505.      that it has enough information to retransmit the final ACK.
  506.  
  507.   o  Realize that TCP sequence numbers wrap around after 2**32 bytes
  508.      have been transferred.  Assume a connection between A.1500 (host A,
  509.      port 1500) and B.2000.  During the connection one segment is lost
  510.      and retransmitted.  But the segment is not really lost, it is held
  511.      by some intermediate router and then re-injected into the network.
  512.      (This is called a "wandering duplicate".)  But in the time between
  513.      the packet being lost & retransmitted, and then reappearing, the
  514.      connection is closed (without any problems) and then another
  515.      connection is established between the same host, same port (that
  516.      is, A.1500 and B.2000; this is called another "incarnation" of the
  517.      connection).  But the sequence numbers chosen for the new
  518.      incarnation just happen to overlap with the sequence number of the
  519.      wandering duplicate that is about to reappear.  (This is indeed
  520.      possible, given the way sequence numbers are chosen for TCP
  521.      connections.)  Bingo, you are about to deliver the data from the
  522.      wandering duplicate (the previous incarnation of the connection) to
  523.      the new incarnation of the connection.  To avoid this, you do not
  524.      allow the same incarnation of the connection to be reestablished
  525.      until the TIME_WAIT state terminates.
  526.  
  527.      Even the TIME_WAIT state doesn't complete solve the second problem,
  528.      given what is called TIME_WAIT assassination.  RFC 1337 has more
  529.      details.
  530.  
  531.   o  The reason that the duration of the TIME_WAIT state is 2*MSL is
  532.      that the maximum amount of time a packet can wander around a
  533.      network is assumed to be MSL seconds.  The factor of 2 is for the
  534.      round-trip.  The recommended value for MSL is 120 seconds, but
  535.      Berkeley-derived implementations normally use 30 seconds instead.
  536.      This means a TIME_WAIT delay between 1 and 4 minutes.  Solaris 2.x
  537.      does indeed use the recommended MSL of 120 seconds.
  538.  
  539.   A wandering duplicate is a packet that appeared to be lost and was
  540.   retransmitted.  But it wasn't really lost ... some router had
  541.   problems, held on to the packet for a while (order of seconds, could
  542.   be a minute if the TTL is large enough) and then re-injects the packet
  543.   back into the network.  But by the time it reappears, the application
  544.   that sent it originally has already retransmitted the data contained
  545.   in that packet.
  546.  
  547.   Because of these potential problems with TIME_WAIT assassinations, one
  548.   should not avoid the TIME_WAIT state by setting the SO_LINGER option
  549.   to send an RST instead of the normal TCP connection termination
  550.   (FIN/ACK/FIN/ACK).  The TIME_WAIT state is there for a reason; it's
  551.   your friend and it's there to help you :-)
  552.  
  553.   I have a long discussion of just this topic in my just-released
  554.   "TCP/IP Illustrated, Volume 3".  The TIME_WAIT state is indeed, one of
  555.   the most misunderstood features of TCP.
  556.  
  557.   I'm currently rewriting "Unix Network Programming" (see ``1.5 Where
  558.   can I get source code for the book [book  title]?''). and will include
  559.   lots more on this topic, as it is often confusing and misunderstood.
  560.  
  561.   An additional note from Andrew:
  562.  
  563.   Closing a socket: if SO_LINGER has not been called on a socket, then
  564.   close() is not supposed to discard data. This is true on SVR4.2 (and,
  565.   apparently, on all non-SVR4 systems) but apparently not on SVR4; the
  566.   use of either shutdown() or SO_LINGER seems to be required to
  567.   guarantee delivery of all data.
  568.  
  569.   2.8.  Why does it take so long to detect that the peer died?
  570.  
  571.   From Andrew Gierth (andrew@erlenstar.demon.co.uk):
  572.  
  573.   Because by default, no packets are sent on the TCP connection unless
  574.   there is data to send or acknowledge.
  575.  
  576.   So, if you are simply waiting for data from the peer, there is no way
  577.   to tell if the peer has silently gone away, or just isn't ready to
  578.   send any more data yet. This can be a problem (especially if the peer
  579.   is a PC, and the user just hits the Big Switch...).
  580.  
  581.   One solution is to use the SO_KEEPALIVE option. This option enables
  582.   periodic probing of the connection to ensure that the peer is still
  583.   present.  BE WARNED: the default timeout for this option is AT LEAST 2
  584.   HOURS.  This timeout can often be altered (in a system-dependent
  585.   fashion) but not normally on a per-connection basis (AFAIK).
  586.  
  587.   RFC1122 specifies that this timeout (if it exists) must be
  588.   configurable.  On the majority of Unix variants, this configuration
  589.   may only be done globally, affecting all TCP connections which have
  590.   keepalive enabled. The method of changing the value, moreover, is
  591.   often difficult and/or poorly documented, and in any case is different
  592.   for just about every version in existence.
  593.  
  594.   If you must change the value, look for something resembling
  595.   tcp_keepidle in your kernel configuration or network options
  596.   configuration.
  597.  
  598.   If you're sending to the peer, though, you have some better
  599.   guarantees; since sending data implies receiving ACKs from the peer,
  600.   then you will know after the retransmit timeout whether the peer is
  601.   still alive. But the retransmit timeout is designed to allow for
  602.   various contingencies, with the intention that TCP connections are not
  603.   dropped simply as a result of minor network upsets. So you should
  604.   still expect a delay of several minutes before getting notification of
  605.   the failure.
  606.  
  607.   The approach taken by most application protocols currently in use on
  608.   the Internet (e.g. FTP, SMTP etc.) is to implement read timeouts on
  609.   the server end; the server simply gives up on the client if no
  610.   requests are received in a given time period (often of the order of 15
  611.   minutes). Protocols where the connection is maintained even if idle
  612.   for long periods have two choices:
  613.  
  614.   1. use SO_KEEPALIVE
  615.  
  616.   2. use a higher-level keepalive mechanism (such as sending a null
  617.      request to the server every so often).
  618.  
  619.   2.9.  What are the pros/cons of select(), non-blocking I/O and SIGIO?
  620.  
  621.   Using non-blocking I/O means that you have to poll sockets to see if
  622.   there is data to be read from them.  Polling should usually be avoided
  623.   since it uses more CPU time than other techniques.
  624.  
  625.   Using SIGIO allows your application to do what it does and have the
  626.   operating system tell it (with a signal) that there is data waiting
  627.   for it on a socket.  The only drawback to this soltion is that it can
  628.   be confusing, and if you are dealing with multiple sockets you will
  629.   have to do a select() anyway to find out which one(s) is ready to be
  630.   read.
  631.  
  632.   Using select() is great if your application has to accept data from
  633.   more than one socket at a time since it will block until any one of a
  634.   number of sockets is ready with data.  One other advantage to select()
  635.   is that you can set a time-out value after which control will be
  636.   returned to you whether any of the sockets have data for you or not.
  637.  
  638.   2.10.  Why do I get EPROTO from read()?
  639.  
  640.   From Steve Rago (sar@plc.com):
  641.  
  642.   EPROTO means that the protocol encountered an unrecoverable error for
  643.   that endpoint.  EPROTO is one of those catch-all error codes used by
  644.   STREAMS-based drivers when a better code isn't available.
  645.  
  646.   And an addition note from Andrew (andrew@erlenstar.demon.co.uk):
  647.  
  648.   Not quite to do with EPROTO from read(), but I found out once that on
  649.   some STREAMS-based implementations, EPROTO could be returned by
  650.   accept() if the incoming connection was reset before the accept
  651.   completes.
  652.  
  653.   On some other implementations, accept seemed to be capable of blocking
  654.   if this occured. This is important, since if select() said the
  655.   listening socket was readable, then you would normally expect not to
  656.   block in the accept() call. The fix is, of course, to set nonblocking
  657.   mode on the listening socket if you are going to use select() on it.
  658.  
  659.   2.11.  How can I force a socket to send the data in it's buffer?
  660.  
  661.   From Richard Stevens (rstevens@noao.edu):
  662.  
  663.   You can't force it.  Period.  TCP makes up its own mind as to when it
  664.   can send data.  Now, normally when you call write() on a TCP socket,
  665.   TCP will indeed send a segment, but there's no guarantee and no way to
  666.   force this.  There are lots of reasons why TCP will not send a
  667.   segment: a closed window and the Nagle algorithm are two things to
  668.   come immediately to mind.
  669.  
  670.   (Snipped suggestion from Andrew Gierth to use TCP_NODELAY)
  671.  
  672.   Setting this only disables one of the many tests, the Nagle algorithm.
  673.   But if the original poster's problem is this, then setting this socket
  674.   option will help.
  675.  
  676.   A quick glance at tcp_output() shows around 11 tests TCP has to make
  677.   as to whether to send a segment or not.
  678.  
  679.   Now from Dr. Charles E. Campbell Jr.  (cec@gryphon.gsfc.nasa.gov):
  680.  
  681.   As you've surmised, I've never had any problem with disabling Nagle's
  682.   algorithm.  Its basically a buffering method; there's a fixed overhead
  683.   for all packets, no matter how small.  Hence, Nagle's algorithm
  684.   collects small packets together (no more than .2sec delay) and thereby
  685.   reduces the amount of overhead bytes being transferred.  This approach
  686.   works well for rcp, for example: the .2 second delay isn't humanly
  687.   noticeable, and multiple users have their small packets more
  688.   efficiently transferred.  Helps in university settings where most
  689.   folks using the network are using standard tools such as rcp and ftp,
  690.   and programs such as telnet may use it, too.
  691.  
  692.   However, Nagle's algorithm is pure havoc for real-time control and not
  693.   much better for keystroke interactive applications (control-C,
  694.   anyone?).  It has seemed to me that the types of new programs using
  695.   sockets that people write usually do have problems with small packet
  696.   delays.  One way to bypass Nagle's algorithm selectively is to use
  697.   "out-of-band" messaging, but that is limited in its content and has
  698.   other effects (such as a loss of sequentiality) (by the way, out-of-
  699.   band is often used for that ctrl-C, too).
  700.  
  701.   More from Vic:
  702.  
  703.   So to sum it all up, if you are having trouble and need to flush the
  704.   socket, setting the TCP_NODELAY option will usually solve the problem.
  705.   If it doesn't, you will have to use out-of-band messaging, but
  706.   according to Andrew, "out-of-band data has its own problems, and I
  707.   don't think it works well as a solution to buffering delays (haven't
  708.   tried it though).  It is not 'expedited data' in the sense that exists
  709.   in some other protocols; it is transmitted in-stream, but with a
  710.   pointer to indicate where it is."
  711.  
  712.   I asked Andrew something to the effect of "What promises does TCP make
  713.   about when it will get around to writing data to the network?"  I
  714.   thought his reply should be put under this question:
  715.  
  716.   Not many promises, but some.
  717.  
  718.   I'll try and quote chapter and verse on this:
  719.  
  720.   References:
  721.  
  722.        RFC 1122, "Requirements for Internet Hosts" (also STD 3)
  723.        RFC  793, "Transmission Control Protocol"   (also STD 7)
  724.  
  725.   1. The socket interface does not provide access to the TCP PUSH flag.
  726.  
  727.   2. RFC1122 says (4.2.2.2):
  728.  
  729.      A TCP MAY implement PUSH flags on SEND calls.  If PUSH flags are
  730.      not implemented, then the sending TCP: (1) must not buffer data
  731.      indefinitely, and (2) MUST set the PSH bit in the last buffered
  732.      segment (i.e., when there is no more queued data to be sent).
  733.  
  734.   3. RFC793 says (2.8):
  735.  
  736.      When a receiving TCP sees the PUSH flag, it must not wait for more
  737.      data from the sending TCP before passing the data to the receiving
  738.      process.
  739.      [RFC1122 supports this statement.]
  740.  
  741.   4. Therefore, data passed to a write() call must be delivered to the
  742.      peer within a finite time, unless prevented by protocol
  743.      considerations.
  744.  
  745.   5. There are (according to a post from Stevens quoted in the FAQ
  746.      [earlier in this answer - Vic]) about 11 tests made which could
  747.      delay sending the data. But as I see it, there are only 2 that are
  748.      significant, since things like retransmit backoff are a) not under
  749.      the programmers control and b) must either resolve within a finite
  750.      time or drop the connection.
  751.  
  752.   The first of the interesting cases is "window closed"  (ie. there is
  753.   no buffer space at the receiver; this can delay data indefinitely, but
  754.   only if the receiving process is not actually reading the data that is
  755.   available)
  756.  
  757.   Vic asks:
  758.  
  759.   OK, it makes sense that if the client isn't reading, the data isn't
  760.   going to make it across the connection.  I take it this causes the
  761.   sender to block after the recieve queue is filled?
  762.  
  763.   The sender blocks when the socket send buffer is full, so buffers will
  764.   be full at both ends.
  765.  
  766.   While the window is closed, the sending TCP sends window probe
  767.   packets. This ensures that when the window finally does open again,
  768.   the sending TCP detects the fact. [RFC1122, ss 4.2.2.17]
  769.  
  770.   The second interesting case is "Nagle algorithm" (small segments, e.g.
  771.   keystrokes, are delayed to form larger segments if ACKs are expected
  772.   from the peer; this is what is disabled with TCP_NODELAY)
  773.  
  774.   Vic Asks:
  775.  
  776.   Does this mean that my tcpclient sample should set TCP_NODELAY to
  777.   ensure that the end-of-line code is indeed put out onto the network
  778.   when sent?
  779.  
  780.   No. tcpclient.c is doing the right thing as it stands; trying to write
  781.   as much data as possible in as few calls to write() as is feasible.
  782.   Since the amount of data is likely to be small relative to the socket
  783.   send buffer, then it is likely (since the connection is idle at that
  784.   point) that the entire request will require only one call to write(),
  785.   and that the TCP layer will immediately dispatch the request as a
  786.   single segment (with the PSH flag, see point 2.2 above).
  787.  
  788.   The Nagle algorithm only has an effect when a second write() call is
  789.   made while data is still unacknowledged. In the normal case, this data
  790.   will be left buffered until either: a) there is no unacknowledged
  791.   data; or b) enough data is available to dispatch a full-sized segment.
  792.   The delay cannot be indefinite, since condition (a) must become true
  793.   within the retransmit timeout or the connection dies.
  794.  
  795.   Since this delay has negative consequences for certain applications,
  796.   generally those where a stream of small requests are being sent
  797.   without response, e.g. mouse movements, the standards specify that an
  798.   option must exist to disable it. [RFC1122, ss 4.2.3.4]
  799.  
  800.   Additional note: RFC1122 also says:
  801.  
  802.      [DISCUSSION]:
  803.         When the PUSH flag is not implemented on SEND calls, i.e., when
  804.         the application/TCP interface uses a pure streaming model,
  805.         responsibility for aggregating any tiny data fragments to form
  806.         reasonable sized segments is partially borne by the application
  807.         layer.
  808.  
  809.   So programs should avoid calls to write() with small data lengths
  810.   (small relative to the MSS, that is); it's better to build up a
  811.   request in a buffer and then do one call to sock_write() or
  812.   equivalent.
  813.  
  814.   The other possible sources of delay in the TCP are not really
  815.   controllable by the program, but they can only delay the data
  816.   temporarily.
  817.  
  818.   Vic asks:
  819.  
  820.   By temporarily, you mean that the data will go as soon as it can, and
  821.   I won't get stuck in a position where one side is waiting on a
  822.   response, and the other side hasn't recieved the request?  (Or at
  823.   least I won't get  stuck forever)
  824.  
  825.   You can only deadlock if you somehow manage to fill up all the buffers
  826.   in both directions... not easy.
  827.  
  828.   If it is possible to do this, (can't think of a good example though),
  829.   the solution is to use nonblocking mode, especially for writes. Then
  830.   you can buffer excess data in the program as necessary.
  831.  
  832.   2.12.  Where can a get a library for programming sockets?
  833.  
  834.   There is the Simple Sockets Library by Charles E. Campbell, Jr. PhD.
  835.   and Terry McRoberts.  The file is called ssl.tar.gz, and you can
  836.   download it from this faq's home page.  For c++ there is the Socket++
  837.   library which is on ftp://ftp.virginia.edu/pub/socket++-1.10.tar.gz.
  838.   There is also C++ Wrappers, but I can't find this package anywhere.
  839.   The file is called C++_wrappers.tar.gz.  I have asked the people where
  840.   it used to be stored where I can find it now, but I never heard back.
  841.   From http://www.cs.wustl.edu/~schmidt you should be able to find the
  842.   ACE toolkit.  PING Software Group has some libraries that include a
  843.   sockets interface among other things.  You can find them at
  844.   http://love.geology.yale.edu/~markl/ping.
  845.  
  846.   I don't have any experience with any of these libraries, so I can't
  847.   recomend one over the other.
  848.  
  849.   2.13.  How come select says there is data, but read returns zero?
  850.  
  851.   The data that causes select to return is the EOF because the other
  852.   side has closed the connection.  This causes read to return zero.  For
  853.   more information see ``2.1 How can I tell when a socket is closed on
  854.   the other end?''
  855.  
  856.   2.14.  Whats the difference between select() and poll()?
  857.  
  858.   From Richard Stevens (rstevens@noao.edu):
  859.  
  860.   The basic difference is that select()'s fd_set is a bit mask and
  861.   therefore has some fixed size.  It would be possible for the kernel to
  862.   not limit this size when the kernel is compiled, allowing the
  863.   application to define FD_SETSIZE to whatever it wants (as the comments
  864.   in the system header imply today) but it takes more work.  4.4BSD's
  865.   kernel and the Solaris library function both have this limit.  But I
  866.   see that BSD/OS 2.1 has now been coded to avoid this limit, so it's
  867.   doable, just a small matter of programming. :-)  Someone should file a
  868.   Solaris bug report on this, and see if it ever gets fixed.
  869.  
  870.   With poll(), however, the user must allocate an array of pollfd
  871.   structures, and pass the number of entries in this array, so there's
  872.   no fundamental limit.  As Casper notes, fewer systems have poll() than
  873.   select, so the latter is more portable.  Also, with original
  874.   implementations (SVR3) you could not set the descriptor to -1 to tell
  875.   the kernel to ignore an entry in the pollfd structure, which made it
  876.   hard to remove entries from the array; SVR4 gets around this.
  877.   Personally, I always use select() and rarely poll(), because I port my
  878.   code to BSD environments too.  Someone could write an implementation
  879.   of poll() that uses select(), for these environments, but I've never
  880.   seen one. Both select() and poll() are being standardized by POSIX
  881.   1003.1g.
  882.  
  883.   2.15.  How do I send [this] over a socket?
  884.  
  885.   Anything other than single bytes of data will probably get mangled
  886.   unless you take care.  For integer values you can use htons() and
  887.   friends, and strings are really just a bunch of single bytes, so those
  888.   should be OK.  Be careful not to send a pointer to a string though,
  889.   since the pointer will be meaningless on another machine.  If you need
  890.   to send a struct, you should write sendthisstruct() and
  891.   readthisstruct() functions for it that do all the work of taking the
  892.   structure apart on one side, and putting it back together on the
  893.   other.  If you need to send floats, you may have a lot of work ahead
  894.   of you.  You should read RFC 1014 which is about portable ways of
  895.   getting data from one machine to another (thanks to Andrew Gabriel for
  896.   pointing this out).
  897.  
  898.   2.16.  How do I use TCP_NODELAY?
  899.  
  900.   First off, be sure you really want to use it in the first place.  It
  901.   will disable the Nagle algorithm (see ``2.11 How can I force a socket
  902.   to send the data in it's buffer?''), which will cause network traffic
  903.   to increase, with smaller than needed packets wasting bandwidth.
  904.   Also, from what I have been able to tell, the speed increase is very
  905.   small, so you should probably do it without TCP_NODELAY first, and
  906.   only turn it on if there is a problem.
  907.  
  908.   Here is a code example, with a warning about using it from Andrew
  909.   Gierth:
  910.  
  911.          int flag = 1;
  912.          int result = setsockopt(sock,            /* socket affected */
  913.                                  IPPROTO_TCP,     /* set option at TCP level */
  914.                                  TCP_NODELAY,     /* name of option */
  915.                                  (char *) &flag,  /* the cast is historical
  916.                                                          cruft */
  917.                                  sizeof(int));    /* length of option value */
  918.          if (result < 0)
  919.             ... handle the error ...
  920.  
  921.   TCP_NODELAY is for a specific purpose; to disable the Nagle buffering
  922.   algorithm. It should only be set for applications that send frequent
  923.   small bursts of information without getting an immediate response,
  924.   where timely delivery of data is required (the canonical example is
  925.   mouse movements).
  926.  
  927.   2.17.  What exactly does the Nagle algorithm do?
  928.  
  929.   It groups together as much data as it can between ACK's from the other
  930.   end of the connection.  I found this really confusing until Andrew
  931.   Gierth (andrew@erlenstar.demon.co.uk) drew the following diagram, and
  932.   explained:
  933.  
  934.   This diagram is not intended to be complete, just to illustrate the
  935.   point better...
  936.  
  937.   Case 1: client writes 1 byte per write() call. The program on host B
  938.   is tcpserver.c from the FAQ examples.
  939.  
  940.              CLIENT                                  SERVER
  941.        APP             TCP                     TCP             APP
  942.                        [connection setup omitted]
  943.  
  944.         "h" --------->          [1 byte]
  945.                            ------------------>
  946.                                                   -----------> "h"
  947.                                           [ack delayed]
  948.         "e" ---------> [Nagle alg.              .
  949.                         now in effect]          .
  950.         "l" ---------> [ditto]                  .
  951.         "l" ---------> [ditto]                  .
  952.         "o" ---------> [ditto]                  .
  953.         "\n"---------> [ditto]                  .
  954.                                                 .
  955.                                                 .
  956.                               [ack 1 byte]
  957.                            <------------------
  958.                        [send queued
  959.                        data]
  960.                                [5 bytes]
  961.                            ------------------>
  962.                                                  ------------> "ello\n"
  963.                                                  <------------ "HELLO\n"
  964.                           [6 bytes, ack 5 bytes]
  965.                            <------------------
  966.         "HELLO\n" <----
  967.                      [ack delayed]
  968.                         .
  969.                         .
  970.                         .   [ack 6 bytes]
  971.                            ------------------>
  972.  
  973.   Total segments: 5. (If TCP_NODELAY was set, could have been up to 10.)
  974.   Time for response: 2*RTT, plus ack delay.
  975.  
  976.   Case 2: client writes all data with one write() call.
  977.  
  978.         CLIENT                                  SERVER
  979.   APP             TCP                     TCP             APP
  980.                   [connection setup omitted]
  981.  
  982.    "hello\n" --->          [6 bytes]
  983.                       ------------------>
  984.                                             ------------> "hello\n"
  985.                                             <------------ "HELLO\n"
  986.                      [6 bytes, ack 6 bytes]
  987.                       <------------------
  988.    "HELLO\n" <----
  989.               [ack delayed]
  990.                    .
  991.                    .
  992.                    .   [ack 6 bytes]
  993.                       ------------------>
  994.  
  995.   Total segments: 3.
  996.  
  997.   Time for response = RTT (therefore minimum possible).
  998.  
  999.   Hope this makes things a bit clearer...
  1000.  
  1001.   Note that in case 2, you don't want the implementation to gratuitously
  1002.   delay sending the data, since that would add straight onto the
  1003.   response time.
  1004.  
  1005.   2.18.  What is the difference between read() and recv()?
  1006.  
  1007.   From Andrew Gierth (andrew@erlenstar.demon.co.uk):
  1008.  
  1009.   read() is equivalent to recv() with a flags parameter of 0.  Other
  1010.   values for the flags parameter change the behaviour of recv().
  1011.   Similarly, write() is equivalent to send() with flags == 0.
  1012.  
  1013.   It is unlikely that send()/recv() would be dropped; perhaps someone
  1014.   with a copy of the POSIX drafts for socket calls can check...
  1015.  
  1016.   Portability note: non-unix systems may not allow read()/write() on
  1017.   sockets, but recv()/send() are usually ok. This is true on Windows and
  1018.   OS/2, for example.
  1019.  
  1020.   2.19.  I see that send()/write() can generate SIGPIPE. Is there any
  1021.   advantage to handling the signal, rather than just ignoring it and
  1022.   checking for the EPIPE error? Are there any useful parameters passed
  1023.   to the signal catching function?
  1024.  
  1025.   From Andrew Gierth (andrew@erlenstar.demon.co.uk):
  1026.  
  1027.   In general, the only parameter passed to a signal handler is the
  1028.   signal number that caused it to be invoked.  Some systems have
  1029.   optional additional parameters, but they are no use to you in this
  1030.   case.
  1031.  
  1032.   My advice is to just ignore SIGPIPE as you suggest. That's what I do
  1033.   in just about all of my socket code; errno values are easier to handle
  1034.   than signals (in fact, the first revision of the FAQ failed to mention
  1035.   SIGPIPE in that context; I'd got so used to ignoring it...)
  1036.  
  1037.   There is one situation where you should not ignore SIGPIPE; if you are
  1038.   going to exec() another program with stdout redirected to a socket. In
  1039.   this case it is probably wise to set SIGPIPE to SIG_DFL before doing
  1040.   the exec().
  1041.  
  1042.   2.20.  After the chroot(), calls to socket() are failing.  Why?
  1043.  
  1044.   From Andrew Gierth (andrew@erlenstar.demon.co.uk):
  1045.  
  1046.   On systems where sockets are implemented on top of Streams (e.g. all
  1047.   SysV-based systems, presumably including Solaris), the socket()
  1048.   function will actually be opening certain special files in /dev. You
  1049.   will need to create a /dev directory under your fake root and populate
  1050.   it with the required device nodes (only).
  1051.  
  1052.   Your system documentation may or may not specify exactly which device
  1053.   nodes are required; I can't help you there (sorry).  (Editors note:
  1054.   Adrian Hall (adrian@waltham.harvard.net) suggested checking the man
  1055.   page for ftpd, which should list the files you need to copy and
  1056.   devices you need to create in the chroot'd environment.)
  1057.  
  1058.   A less-obvious issue with chroot() is if you call syslog(), as many
  1059.   daemons do; syslog() opens (depending on the system) either a UDP
  1060.   socket, a FIFO or a Unix-domain socket. So if you use it after a
  1061.   chroot() call, make sure that you call openlog() *before* the chroot.
  1062.  
  1063.   2.21.  Why do I keep getting EINTR from the socket calls?
  1064.  
  1065.   This isn't really so much an error as an exit condition.  It means
  1066.   that the call was interrupted by a signal.  Any call that might block
  1067.   should be wrapped in a loop that checkes for EINTR, as is done in the
  1068.   example code (See ``6. Sample Source Code'').
  1069.  
  1070.   2.22.  When will my application receive SIGPIPE?
  1071.  
  1072.   From Richard Stevens (rstevens@noao.edu):
  1073.  
  1074.   Very simple: with TCP you get SIGPIPE if your end of the connection
  1075.   has received an RST from the other end.  What this also means is that
  1076.   if you were using select instead of write, the select would have
  1077.   indicated the socket as being readable, since the RST is there for you
  1078.   to read (read will return an error with errno set to ECONNRESET).
  1079.  
  1080.   Basically an RST is TCP's response to some packet that it doesn't
  1081.   expect and has no other way of dealing with.  A common case is when
  1082.   the peer closes the connection (sending you a FIN) but you ignore it
  1083.   because you're writing and not reading.  (You should be using select.)
  1084.   So you write to a connection that has been closed by the other end and
  1085.   the oether end's TCP responds with an RST.
  1086.  
  1087.   2.23.  What are socket exceptions?  What is out-of-band data?
  1088.  
  1089.   Unlike exceptions in C++, socket exceptions do not indicate that an
  1090.   error has occured.  Socket exceptions usually refer to the
  1091.   notification that out-of-band data has arrived.  Out-of-band data
  1092.   (called "urgent data" in TCP) looks to the application like a separate
  1093.   stream of data from the main data stream.  This can be useful for
  1094.   separating two different kinds of data.  Note that just because it is
  1095.   called "urgent data" does not mean that it will be delivered any
  1096.   faster, or with higher priorety than data in the in-band data stream.
  1097.   Also beware that unlike the main data stream, the out-of-bound data
  1098.   may be lost if your application can't keep up with it.
  1099.  
  1100.   2.24.  running on?  How can I find the full hostname (FQDN) of the
  1101.   system I'm
  1102.  
  1103.   From Richard Stevens (rstevens@noao.edu):
  1104.  
  1105.   Some systems set the hostname to the FQDN and others set it to just
  1106.   the unqualified host name.  I know the current BIND FAQ recommends the
  1107.   FQDN, but most Solaris systems, for example, tend to use only the
  1108.   unqualified host name.
  1109.  
  1110.   Regardless, the way around this is to first get the host's name
  1111.   (perhaps an FQDN, perhaps unaualified).  Most systems support the
  1112.   Posix way to do this using uname(), but older BSD systems only provide
  1113.   gethostname().  Call gethostbyname() to find your IP address.  Then
  1114.   take the IP address and call gethostbyaddr().  The h_name member of
  1115.   the hostent{} should then be your FQDN.
  1116.  
  1117.   2.25.  How would I put my socket in non-blocking mode?
  1118.  
  1119.   From Andrew Gierth (andrew@erlenstar.demon.co.uk):
  1120.  
  1121.   Technically, fcntl(soc, F_SETFL, O_NONBLOCK) is incorrect since it
  1122.   clobbers all other file flags. Generally one gets away with it since
  1123.   the other flags (O_APPEND for example) don't really apply much to
  1124.   sockets. In a similarly rough vein, you would use fcntl(soc, F_SETFL,
  1125.   0) to go back to blocking mode.
  1126.  
  1127.   To do it right, use F_GETFL to get the current flags, set or clear the
  1128.   O_NONBLOCK flag, then use F_SETFL to set the flags.
  1129.  
  1130.   And yes, the flag can be changed either way at will.
  1131.  
  1132.   3.  Writing Client Applications (TCP/SOCK_STREAM)
  1133.  
  1134.   3.1.  How do I convert a string into an internet address?
  1135.  
  1136.   If you are reading a host's address from the command line, you may not
  1137.   know if you have an aaa.bbb.ccc.ddd style address, or a
  1138.   host.domain.com style address.  What I do with these, is first try to
  1139.   use it as a aaa.bbb.ccc.ddd type address, and if that fails, then do a
  1140.   name lookup on it.  Here is an example:
  1141.  
  1142.        /* Converts ascii text to in_addr struct.  NULL is returned if the
  1143.           address can not be found. */
  1144.        struct in_addr *atoaddr(char *address) {
  1145.          struct hostent *host;
  1146.          static struct in_addr saddr;
  1147.  
  1148.          /* First try it as aaa.bbb.ccc.ddd. */
  1149.          saddr.s_addr = inet_addr(address);
  1150.          if (saddr.s_addr != -1) {
  1151.            return &saddr;
  1152.          }
  1153.          host = gethostbyname(address);
  1154.          if (host != NULL) {
  1155.            return (struct in_addr *) *host->h_addr_list;
  1156.          }
  1157.          return NULL;
  1158.        }
  1159.  
  1160.   3.2.  How can my client work through a firewall/proxy server?
  1161.  
  1162.   If you are running through separate proxies for each service, you
  1163.   shouldn't need to do anything.  If you are working through sockd, you
  1164.   will need to "socksify" your application.  Details for doing this can
  1165.   be found in the package itself, which is available at:
  1166.  
  1167.        ftp://ftp.net.com/socks.cstc/socks.cstc.4.2.tar.gz
  1168.  
  1169.   you can get the socks faq at:
  1170.  
  1171.        ftp://coast.cs.purdue.edu/pub/tools/unix/socks/FAQ
  1172.  
  1173.   3.3.  Why does connect() succeed even before my server did an
  1174.   accept()?
  1175.  
  1176.   From Andrew Gierth (andrew@erlenstar.demon.co.uk):
  1177.  
  1178.   Once you have done a listen() call on your socket, the kernel is
  1179.   primed to accept connections on it. The usual UNIX implementation of
  1180.   this works by immediately completing the SYN handshake for any
  1181.   incoming valid SYN segments (connection attempts), creating the socket
  1182.   for the new connection, and keeping this new socket on an internal
  1183.   queue ready for the accept() call. So the socket is fully open before
  1184.   the accept is done.
  1185.  
  1186.   The other factor in this is the 'backlog' parameter for listen(); that
  1187.   defines how many of these completed connections can be queued at one
  1188.   time.  If the specified number is exceeded, then new incoming connects
  1189.   are simply ignored (which causes them to be retried).
  1190.  
  1191.   3.4.  Why do I sometimes loose a server's address when using more than
  1192.   one server?
  1193.  
  1194.   From Andrew Gierth (andrew@erlenstar.demon.co.uk):
  1195.  
  1196.   Take a careful look at struct hostent. Notice that almost everything
  1197.   in it is a pointer? All these pointers will refer to statically
  1198.   allocated data.
  1199.  
  1200.   For example, if you do:
  1201.  
  1202.            struct hostent *host = gethostbyname(hostname);
  1203.  
  1204.   then (as you should know) a subsequent call to gethostbyname() will
  1205.   overwrite the structure pointed to by 'host'.
  1206.  
  1207.   But if you do:
  1208.  
  1209.            struct hostent myhost;
  1210.            struct hostent *hostptr = gethostbyname(hostname);
  1211.            if (hostptr) myhost = *host;
  1212.  
  1213.   to make a copy of the hostent before it gets overwritten, then it
  1214.   still gets clobbered by a subsequent call to gethostbyname(), since
  1215.   although myhost won't get overwritten, all the data it is pointing to
  1216.   will be.
  1217.  
  1218.   You can get round this by doing a proper 'deep copy' of the hostent
  1219.   structure, but this is tedious. My recommendation would be to extract
  1220.   the needed fields of the hostent and store them in your own way.
  1221.  
  1222.   3.5.  How can I set the timeout for the connect() system call?
  1223.  
  1224.   From Richard Stevens (rstevens@noao.edu):
  1225.  
  1226.   Normally you cannot change this.  Solaris does let you do this, on a
  1227.   per-kernel basis with the ndd tcp_ip_abort_cinterval parameter.
  1228.  
  1229.   The easiest way to shorten the connect time is with an alarm() around
  1230.   the call to connect().  A harder way is to use select(), after setting
  1231.   the socket nonblocking.  Also notice that you can only shorten the
  1232.   connect time, there's normally no way to lengthen it.
  1233.  
  1234.   From Andrew Gierth (andrew@erlenstar.demon.co.uk):
  1235.  
  1236.   First, create the socket and put it into non-blocking mode, then call
  1237.   connect(). There are three possibilities:
  1238.  
  1239.   o  connect succeeds: the connection has been successfully made (this
  1240.      usually only happens when connecting to the same machine)
  1241.  
  1242.   o  connect fails: obvious
  1243.  
  1244.   o  connect returns -1/EINPROGRESS. The connection attempt has begun,
  1245.      but not yet completed.
  1246.  
  1247.   If the connection succeeds:
  1248.  
  1249.   o  the socket will select() as writable (and will also select as
  1250.      readable if data arrives)
  1251.  
  1252.   If the connection fails:
  1253.  
  1254.   o  the socket will select as readable *and* writable, but either a
  1255.      read or write will return the error code from the connection
  1256.      attempt. Also, you can use getsockopt(SO_ERROR) to get the error
  1257.      status - but be careful; some systems return the error code in the
  1258.      result parameter of getsockopt, but others (incorrectly) cause the
  1259.      getsockopt call *itself* to fail with the stored value as the
  1260.      error.
  1261.  
  1262.   3.6.  system choose one for me on the connect() call?  Should I bind()
  1263.   a port number in my client program, or let the
  1264.  
  1265.   From Andrew Gierth (andrew@erlenstar.demon.co.uk):
  1266.  
  1267.   ** Let the system choose your client's port number **
  1268.  
  1269.   The exception to this, is if the server has been written to be picky
  1270.   about what client ports it will allow connections from. Rlogind and
  1271.   rshd are the classic examples. This is usually part of a Unix-specific
  1272.   (and rather weak) authentication scheme; the intent is that the server
  1273.   allows connections only from processes with root privilege. (The
  1274.   weakness in the scheme is that many O/Ss (e.g. MS-DOS) allow anyone to
  1275.   bind any port.)
  1276.  
  1277.   The rresvport() routine exists to help out clients that are using this
  1278.   scheme. It basically does the equivalent of socket() + bind(),
  1279.   choosing a port number in the range 512..1023.
  1280.  
  1281.   If the server is not fussy about the client's port number, then don't
  1282.   try and assign it yourself in the client, just let connect() pick it
  1283.   for you.
  1284.  
  1285.   If, in a client, you use the naive scheme of starting at a fixed port
  1286.   number and calling bind() on consecutive values until it works, then
  1287.   you buy yourself a whole lot of trouble:
  1288.  
  1289.   The problem is if the server end of your connection does an active
  1290.   close.  (E.G. client sends 'QUIT' command to server, server responds
  1291.   by closing the connection). That leaves the client end of the
  1292.   connection in CLOSED state, and the server end in TIME_WAIT state. So
  1293.   after the client exits, there is no trace of the connection on the
  1294.   client end.
  1295.  
  1296.   Now run the client again. It will pick the same port number, since as
  1297.   far as it can see, it's free. But as soon as it calls connect(), the
  1298.   server finds that you are trying to duplicate an existing connection
  1299.   (although one in TIME_WAIT). It is perfectly entitled to refuse to do
  1300.   this, so you get, I suspect, ECONNREFUSED from connect(). (Some
  1301.   systems may sometimes allow the connection anyway, but you can't rely
  1302.   on it.)
  1303.  
  1304.   This problem is especially dangerous because it doesn't show up unless
  1305.   the client and server are on different machines. (If they are the same
  1306.   machine, then the client won't pick the same port number as before).
  1307.   So you can get bitten well into the development cycle (if you do what
  1308.   I suspect most people do, and test client & server on the same box
  1309.   initially).
  1310.  
  1311.   Even if your protocol has the client closing first, there are still
  1312.   ways to produce this problem (e.g. kill the server).
  1313.  
  1314.   3.7.  Why do I get "connection refused" when the server isn't running?
  1315.  
  1316.   The connect() call will only block while it is waiting to establish a
  1317.   connection.  When there is no server waiting at the other end, it gets
  1318.   notified that the connection can not be established, and gives up with
  1319.   the error message you see.  This is a good thing, since if it were not
  1320.   the case clients might wait for ever for a service which just doesn't
  1321.   exist.  Users would think that they were only waiting for the
  1322.   connection to be established, and then after a while give up,
  1323.   muttering something about crummy software under their breath.
  1324.  
  1325.   3.8.  over the socket ? Is there a way to have a dynamic buffer ?
  1326.   What does one do when one does not know how much information is com-
  1327.   ming
  1328.  
  1329.   This question asked by Niranjan Perera (perera@mindspring.com).
  1330.  
  1331.   When the size of the incoming data is unknown, you can either make the
  1332.   size of the buffer as big as the largest possible (or likely) buffer,
  1333.   or you can re-size the buffer on the fly during your read.  When you
  1334.   malloc() a large buffer, most (if not all) varients of unix will only
  1335.   allocate address space, but not physical pages of ram.  As more and
  1336.   more of the buffer is used, the kernel allocates physical memory.
  1337.   This means that malloc'ing a large buffer will not waste resources
  1338.   unless that memory is used, and so it is perfectly acceptable to ask
  1339.   for a meg of ram when you expect only a few K.
  1340.  
  1341.   On the other hand, a more elegant solution that does not depend on the
  1342.   inner workings of the kernel is to use realloc() to expand the buffer
  1343.   as required in say 4K chunks (since 4K is the size of a page of ram on
  1344.   most systems).  I may add something like this to sockhelp.c in the
  1345.   example code one day.
  1346.  
  1347.   4.  Writing Server Applications (TCP/SOCK_STREAM)
  1348.  
  1349.   4.1.  How come I get "address already in use" from bind()?
  1350.  
  1351.   You get this when the address is already in use.  (Oh, you figured
  1352.   that much out?)  The most common reason for this is that you have
  1353.   stopped your server, and then re-started it right away.  The sockets
  1354.   that were used by the first incarnation of the server are still
  1355.   active.  This is further explained in ``2.7 Please explain the
  1356.   TIME_WAIT state.'', and ``2.5 How do I properly close a socket?''.
  1357.  
  1358.   4.2.  Why don't my sockets close?
  1359.  
  1360.   When you issue the close() system call, you are closing your interface
  1361.   to the socket, not the socket itself.  It is up to the kernel to close
  1362.   the socket.  Sometimes, for really technical reasons, the socket is
  1363.   kept alive for a few minutes after you close it.  It is normal, for
  1364.   example for the socket to go into a TIME_WAIT state, on the server
  1365.   side, for a few minutes.  People have reported ranges from 20 seconds
  1366.   to 4 minutes to me.  The official standard says that it should be 4
  1367.   minutes.  On my Linux system it is about 2 minutes.  This is explained
  1368.   in great detail in ``2.7 Please explain the TIME_WAIT state.''.
  1369.  
  1370.   4.3.  How can I make my server a daemon?
  1371.  
  1372.   There are two approaches you can take here.  The first is to use inetd
  1373.   to do all the hard work for you.  The second is to do all the hard
  1374.   work yourself.
  1375.  
  1376.   If you use inetd, you simply use stdin, stdout, or stderr for your
  1377.   socket.  (These three are all created with dup() from the real socket)
  1378.   You can use these as you would a socket in your code.  The inetd
  1379.   process will even close the socket for you when you are done.
  1380.  
  1381.   If you wish to write your own server, there is a detailed explanation
  1382.   in "Unix Network Programming" by Richard Stevens (see ``1.5 Where can
  1383.   I get source code for the book [book  title]?''). I also picked up
  1384.   this posting from comp.unix.programmer, by Nikhil Nair
  1385.   (nn201@cus.cam.ac.uk).  You may want to add code to ignore SIGPIPE,
  1386.   because if this signal is not dealt with, it will cause your
  1387.   application to exit.  (Thanks to ingo@milan2.snafu.de for pointing
  1388.   this out).
  1389.  
  1390.   I worked all this lot out from the GNU C Library Manual (on-line
  1391.   documentation).  Here's some code I wrote - you can adapt it as necessary:
  1392.  
  1393.   #include <stdio.h>
  1394.   #include <stdlib.h>
  1395.   #include <ctype.h>
  1396.   #include <unistd.h>
  1397.   #include <fcntl.h>
  1398.   #include <signal.h>
  1399.   #include <sys/wait.h>
  1400.  
  1401.   /* Global variables */
  1402.   volatile sig_atomic_t keep_going = 1; /* controls program termination */
  1403.  
  1404.   /* Function prototypes: */
  1405.   void termination_handler (int signum); /* clean up before termination */
  1406.  
  1407.   int
  1408.   main (void)
  1409.   {
  1410.     ...
  1411.  
  1412.     if (chdir (HOME_DIR))         /* change to directory containing data
  1413.                                       files */
  1414.      {
  1415.        fprintf (stderr, "`%s': ", HOME_DIR);
  1416.        perror (NULL);
  1417.        exit (1);
  1418.      }
  1419.  
  1420.      /* Become a daemon: */
  1421.      switch (fork ())
  1422.        {
  1423.        case -1:                    /* can't fork */
  1424.          perror ("fork()");
  1425.          exit (3);
  1426.        case 0:                     /* child, process becomes a daemon: */
  1427.          close (STDIN_FILENO);
  1428.          close (STDOUT_FILENO);
  1429.          close (STDERR_FILENO);
  1430.          if (setsid () == -1)      /* request a new session (job control) */
  1431.            {
  1432.              exit (4);
  1433.            }
  1434.          break;
  1435.        default:                    /* parent returns to calling process: */
  1436.          return 0;
  1437.        }
  1438.  
  1439.      /* Establish signal handler to clean up before termination: */
  1440.      if (signal (SIGTERM, termination_handler) == SIG_IGN)
  1441.        signal (SIGTERM, SIG_IGN);
  1442.      signal (SIGINT, SIG_IGN);
  1443.      signal (SIGHUP, SIG_IGN);
  1444.  
  1445.      /* Main program loop */
  1446.      while (keep_going)
  1447.        {
  1448.          ...
  1449.        }
  1450.      return 0;
  1451.   }
  1452.  
  1453.   void
  1454.   termination_handler (int signum)
  1455.   {
  1456.     keep_going = 0;
  1457.     signal (signum, termination_handler);
  1458.   }
  1459.  
  1460.   4.4.  How can I listen on more than one port at a time?
  1461.  
  1462.   The best way to do this is with the select() call.  This tells the
  1463.   kernel to let you know when a socket is available for use.  You can
  1464.   have one process do i/o with multiple sockets with this call.  If you
  1465.   want to wait for a connect on sockets 4, 6 and 10 you might execute
  1466.   the following code snippet:
  1467.  
  1468.        fd_set socklist;
  1469.  
  1470.        FD_ZERO(&socklist); /* Always clear the structure first. */
  1471.        FD_SET(4, &socklist);
  1472.        FD_SET(6, &socklist);
  1473.        FD_SET(10, &socklist);
  1474.        if (select(11, NULL, &socklist, NULL, NULL) < 0)
  1475.          perror("select");
  1476.  
  1477.   The kernel will notify us as soon as a file descriptor which is less
  1478.   than 11 (the first parameter to select()), and is a member of our
  1479.   socklist becomes available for writing.  See the man page on select()
  1480.   for more details.
  1481.  
  1482.   4.5.  What exactly does SO_REUSEADDR do?
  1483.  
  1484.   This socket option tells the kernel that even if this port is busy, go
  1485.   ahead and reuse it anyway.  It is useful if your server has been shut
  1486.   down, and then restarted right away while sockets are still active on
  1487.   its port.  You should be aware that if any unexpected data comes in,
  1488.   it may confuse your server, but while this is possible, it is not
  1489.   likely.
  1490.  
  1491.   It has been pointed out that "A socket is a 5 tuple (proto, local
  1492.   addr, local port, remote addr, remote port).  SO_REUSEADDR just says
  1493.   that you can reuse local addresses.  The 5 tuple still must be
  1494.   unique!" by Michael Hunter (mphunter@qnx.com).  This is true, and this
  1495.   is why it is very unlikely that unexpected data will ever be seen by
  1496.   your server.  The danger is that such a 5 tuple is still floating
  1497.   around on the net, and while it is bouncing around, a new connection
  1498.   from the same client, on the same system, happens to get the same
  1499.   remote port.  This is explained by Richard Stevens in ``2.7 Please
  1500.   explain the TIME_WAIT state.''.
  1501.  
  1502.   4.6.  What exactly does SO_LINGER do?
  1503.  
  1504.   On some unixes this does nothing.  On others, it instructs the kernel
  1505.   to abort tcp connections instead of closing them properly.  This can
  1506.   be dangerous.  If you are not clear on this, see ``2.7 Please explain
  1507.   the TIME_WAIT state.''.
  1508.   4.7.  What exactly does SO_KEEPALIVE do?
  1509.  
  1510.   From Andrew Gierth (andrew@erlenstar.demon.co.uk):
  1511.  
  1512.   The SO_KEEPALIVE option causes a packet (called a 'keepalive probe')
  1513.   to be sent to the remote system if a long time (by default, more than
  1514.   2 hours) passes with no other data being sent or received. This packet
  1515.   is designed to provoke an ACK response from the peer. This enables
  1516.   detection of a peer which has become unreachable (e.g. powered off or
  1517.   disconnected from the net).  See ``2.8 Why does it take so long to
  1518.   detect that the peer died?''  for further discussion.
  1519.  
  1520.   Note that the figure of 2 hours comes from RFC1122, "Requirements for
  1521.   Internet Hosts". The precise value should be configurable, but I've
  1522.   often found this to be difficult.  The only implementation I know of
  1523.   that allows the keepalive interval to be set per-connection is SVR4.2.
  1524.  
  1525.   4.8.  How can I bind() to a port number < 1024?
  1526.  
  1527.   From Andrew Gierth (andrew@erlenstar.demon.co.uk):
  1528.  
  1529.   The restriction on access to ports < 1024 is part of a (fairly weak)
  1530.   security scheme particular to UNIX. The intention is that servers (for
  1531.   example rlogind, rshd) can check the port number of the client, and if
  1532.   it is < 1024, assume the request has been properly authorised at the
  1533.   client end.
  1534.  
  1535.   The practical upshot of this, is that binding a port number < 1024 is
  1536.   reserved to processes having an effective UID == root.
  1537.  
  1538.   This can, occasionally, itself present a security problem, e.g. when a
  1539.   server process needs to bind a well-known port, but does not itself
  1540.   need root access (news servers, for example). This is often solved by
  1541.   creating a small program which simply binds the socket, then restores
  1542.   the real userid and exec()s the real server. This program can then be
  1543.   made setuid root.
  1544.  
  1545.   4.9.  How do I get my server to find out the client's address / host-
  1546.   name?
  1547.  
  1548.   From Andrew Gierth (andrew@erlenstar.demon.co.uk):
  1549.  
  1550.   After accept()ing a connection, use getpeername() to get the address
  1551.   of the client.  The client's address is of course, also returned on
  1552.   the accept(), but it is essential to initialise the address-length
  1553.   parameter before the accept call for this will work.
  1554.  
  1555.   Jari Kokko (jkokko@cc.hut.fi) has offered the following code to
  1556.   determine the client address:
  1557.  
  1558.   int t;
  1559.   int len;
  1560.   struct sockaddr_in sin;
  1561.   struct hostent *host;
  1562.  
  1563.   len = sizeof sin;
  1564.   if (getpeername(t, (struct sockaddr *) &sin, &len) < 0)
  1565.           perror("getpeername");
  1566.   else {
  1567.           if ((host = gethostbyaddr((char *) &sin.sin_addr,
  1568.                                     sizeof sin.sin_addr,
  1569.                                     AF_INET)) == NULL)
  1570.               perror("gethostbyaddr");
  1571.           else printf("remote host is '%s'\n", host->h_name);
  1572.   }
  1573.  
  1574.   4.10.  How should I choose a port number for my server?
  1575.  
  1576.   The list of registered port assignments can be found in STD 2 or RFC
  1577.   1700.  Choose one that isn't already registered, and isn't in
  1578.   /etc/services on your system.  It is also a good idea to let users
  1579.   customize the port number in case of conflicts with other un-
  1580.   registered port numbers in other servers.  The best way of doing this
  1581.   is hardcoding a service name, and using getservbyname() to lookup the
  1582.   actual port number.  This method allows users to change the port your
  1583.   server binds to by simply editing the /etc/services file.
  1584.  
  1585.   4.11.  What is the difference between SO_REUSEADDR and SO_REUSEPORT?
  1586.  
  1587.   SO_REUSEADDR allows your server to bind to an address which is in a
  1588.   TIME_WAIT state.  It does not allow more than one server to bind to
  1589.   the same address.  It was mentioned that use of this flag can create a
  1590.   security risk because another server can bind to a the same port, by
  1591.   binding to a specific address as opposed to INADDR_ANY.  The
  1592.   SO_REUSEPORT flag allows multiple processes to bind to the same
  1593.   address provided all of them use the SO_REUSEPORT option.
  1594.  
  1595.   From Richard Stevens (rstevens@noao.edu):
  1596.  
  1597.   This is a newer flag that appeared in the 4.4BSD multicasting code
  1598.   (although that code was from elsewhere, so I am not sure just who
  1599.   invented the new SO_REUSEPORT flag).
  1600.  
  1601.   What this flag lets you do is rebind a port that is already in use,
  1602.   but only if all users of the port specify the flag.  I believe the
  1603.   intent is for multicasting apps, since if you're running the same app
  1604.   on a host, all need to bind the same port.  But the flag may have
  1605.   other uses.  For example the following is from a post in February:
  1606.  
  1607.   From Stu Friedberg (stuartf@sequent.com):
  1608.  
  1609.        SO_REUSEPORT is also useful for eliminating the
  1610.        try-10-times-to-bind hack in ftpd's data connection setup
  1611.        routine.  Without SO_REUSEPORT, only one ftpd thread can
  1612.        bind to TCP (lhost, lport, INADDR_ANY, 0) in preparation for
  1613.        connecting back to the client.  Under conditions of heavy
  1614.        load, there are more threads colliding here than the
  1615.        try-10-times hack can accomodate.  With SO_REUSEPORT, things
  1616.        work nicely and the hack becomes unnecessary.
  1617.  
  1618.   I have also heard that DEC OSF supports the flag.  Also note that
  1619.   under 4.4BSD, if you are binding a multicast address, then
  1620.   SO_REUSEADDR is condisered the same as SO_REUSEPORT (p. 731 of "TCP/IP
  1621.   Illustrated, Volume 2").  I think under Solaris you just replace
  1622.   SO_REUSEPORT with SO_REUSEADDR.
  1623.  
  1624.   From a later Stevens posting, with minor editing:
  1625.  
  1626.   Basically SO_REUSEPORT is a BSD'ism that arose when multicasting was
  1627.   added, even thought it was not used in the original Steve Deering
  1628.   code.  I believe some BSD-derived systems may also include it (OSF,
  1629.   now Digital Unix, perhaps?).  SO_REUSEPORT lets you bind the same
  1630.   address *and* port, but only if all the binders have specified it.
  1631.   But when binding a multicast address (its main use), SO_REUSEADDR is
  1632.   considered identical to SO_REUSEPORT (p. 731, "TCP/IP Illustrated,
  1633.   Volume 2").  So for portability of multicasting applications I always
  1634.   use SO_REUSEADDR.
  1635.  
  1636.   4.12.  How can I write a multi-homed server?
  1637.  
  1638.   The original question was actually from Shankar Ramamoorthy
  1639.   (shankar@viman.com):
  1640.  
  1641.        I want to run a server on a multi-homed host. The host is
  1642.        part of two networks and has two ethernet cards. I want to
  1643.        run a server on this machine, binding to a pre-determined
  1644.        port number. I want clients on either subnet to be able to
  1645.        send broadcast packates to the port and have the server
  1646.        receive them.
  1647.  
  1648.   And answered by Andrew Gierth (andrew@erlenstar.demon.co.uk):
  1649.  
  1650.   Your first question in this scenario is, do you need to know which
  1651.   subnet the packet came from? I'm not at all sure that this can be
  1652.   reliably determined in all cases.
  1653.  
  1654.   If you don't really care, then all you need is one socket bound to
  1655.   INADDR_ANY. That simplifies things greatly.
  1656.  
  1657.   If you do care, then you have to bind multiple sockets. You are
  1658.   obviously attempting to do this in your code as posted, so I'll assume
  1659.   you do.
  1660.  
  1661.        I was hoping that something like the following would work.
  1662.        Will it?  This is on Sparcs running Solaris 2.4/2.5.
  1663.  
  1664.   I don't have access to Solaris, but I'll comment based on my
  1665.   experience with other Unixes.
  1666.  
  1667.   [Shankar's original code omitted]
  1668.  
  1669.   What you are doing is attempting to bind all the current hosts unicast
  1670.   addresses as listed in hosts/NIS/DNS. This may or may not reflect
  1671.   reality, but much more importantly, neglects the broadcast addresses.
  1672.   It seems to be the case in the majority of implementations that a
  1673.   socket bound to a unicast address will not see incoming packets with
  1674.   broadcast addresses as their destinations.
  1675.  
  1676.   The approach I've taken is to use SIOCGIFCONF to retrieve the list of
  1677.   active network interfaces, and SIOCGIFFLAGS and SIOCGIFBRDADDR to
  1678.   identify broadcastable interfaces and get the broadcast addresses.
  1679.   Then I bind to each unicast address, each broadcast address, and to
  1680.   INADDR_ANY as well. That last is necessary to catch packets that are
  1681.   on the wire with INADDR_BROADCAST in the destination.  (SO_REUSEADDR
  1682.   is necessary to bind INADDR_ANY as well as the specific addresses.)
  1683.  
  1684.   This gives me very nearly what I want. The wrinkles are:
  1685.  
  1686.   o  I don't assume that getting a packet through a particular socket
  1687.      necessarily means that it actually arrived on that interface.
  1688.  
  1689.   o  I can't tell anything about which subnet a packet originated on if
  1690.      it's destination was INADDR_BROADCAST.
  1691.  
  1692.   o  On some stacks, apparently only those with multicast support, I get
  1693.      duplicate incoming messages on the INADDR_ANY socket.
  1694.  
  1695.   4.13.  How can I read only one character at a time?
  1696.  
  1697.   This question is usually asked by people who are testing their server
  1698.   with telnet, and want it to process their keystrokes one character at
  1699.   a time.  The correct technique is to use a psuedo terminal (pty).
  1700.   More on that in a minute.
  1701.  
  1702.   According to Roger Espel Llima (espel@drakkar.ens.fr), you can have
  1703.   your server send a sequence of control characters: 0xff 0xfb 0x01 0xff
  1704.   0xfb 0x03 0xff 0xfd 0x0f3, which translates to IAC WILL ECHO IAC WILL
  1705.   SUPPRESS-GO-AHEAD IAC DO SUPPRESS-GO-AHEAD.  For more information on
  1706.   what this means, check out std8, std28 and std29.  Roger also gave the
  1707.   following tips:
  1708.  
  1709.   o  This code will suppress echo, so you'll have to send the characters
  1710.      the user types back to the client if you want the user to see them.
  1711.  
  1712.   o  Carriage returns will be followed by a null character, so you'll
  1713.      have to expect them.
  1714.  
  1715.   o  If you get a 0xff, it will be followed by two more characters.
  1716.      These are telnet escapes.
  1717.  
  1718.   Use of a pty would also be the correct way to execute a child process
  1719.   and pass the i/o to a socket.
  1720.  
  1721.   I'll add pty stuff to the list of example source I'd like to add to
  1722.   the faq.  If someone has some source they'd like to contribute
  1723.   (without copyright) to the faq which demonstrates use of pty's, please
  1724.   email me!
  1725.  
  1726.   4.14.  I'm trying to exec() a program from my server, and attach my
  1727.   socket's IO to it, but I'm not getting all the data across.  Why?
  1728.  
  1729.   If the program you are running uses printf(), etc (streams from
  1730.   stdio.h) you have to deal with two buffers.  The kernel buffers all
  1731.   socket IO, and this is explained in ``section 2.11''.  The second
  1732.   buffer is the one that is causing you grief.  This is the stdio
  1733.   buffer, and the problem was well explained by Andrew:
  1734.  
  1735.   (The short answer to this question is that you want to use a pty
  1736.   rather than a socket; the remainder of this article is an attempt to
  1737.   explain why.)
  1738.  
  1739.   Firstly, the socket buffer controlled by setsockopt() has absolutly
  1740.   nothing to do with stdio buffering. Setting it to 1 is guaranteed to
  1741.   be the Wrong Thing(tm).
  1742.   Perhaps the following diagram might make things a little clearer:
  1743.  
  1744.                Process A                   Process B
  1745.            +---------------------+     +---------------------+
  1746.            |                     |     |                     |
  1747.            |    mainline code    |     |    mainline code    |
  1748.            |         |           |     |         ^           |
  1749.            |         v           |     |         |           |
  1750.            |      fputc()        |     |      fgetc()        |
  1751.            |         |           |     |         ^           |
  1752.            |         v           |     |         |           |
  1753.            |    +-----------+    |     |    +-----------+    |
  1754.            |    | stdio     |    |     |    | stdio     |    |
  1755.            |    | buffer    |    |     |    | buffer    |    |
  1756.            |    +-----------+    |     |    +-----------+    |
  1757.            |         |           |     |         ^           |
  1758.            |         |           |     |         |           |
  1759.            |      write()        |     |       read()        |
  1760.            |         |           |     |         |           |
  1761.            +-------- | ----------+     +-------- | ----------+
  1762.                      |                           |                  User space
  1763.          ------------|-------------------------- | ---------------------------
  1764.                      |                           |                Kernel space
  1765.                      v                           |
  1766.                 +-----------+               +-----------+
  1767.                 | socket    |               | socket    |
  1768.                 | buffer    |               | buffer    |
  1769.                 +-----------+               +-----------+
  1770.                      |                           ^
  1771.                      v                           |
  1772.              (AF- and protocol-          (AF- and protocol-
  1773.               dependent code)             dependent code)
  1774.  
  1775.   Assuming these two processes are communicating with each other (I've
  1776.   deliberately omitted the actual comms mechanisms, which aren't really
  1777.   relevent), you can see that data written by process A to it's stdio
  1778.   buffer is completely inaccessible to process B. Only once the decision
  1779.   is made to flush that buffer to the kernel (via write()) can the data
  1780.   actually be delivered to the other process.
  1781.  
  1782.   The only guaranteed way to affect the buffering within process A is to
  1783.   change the code. However, the default buffering for stdout is
  1784.   controlled by whether the underlying FD refers to a terminal or not;
  1785.   generally, output to terminals is line-buffered, and output to non-
  1786.   terminals (including but not limited to files, pipes, sockets, non-tty
  1787.   devices, etc.) is fully buffered. So the desired effect can usually be
  1788.   achieved by using a pty device; this, for example, is what the
  1789.   'expect' program does.
  1790.  
  1791.   Since the stdio buffer (and the FILE structure, and everything else
  1792.   related to stdio) is user-level data, it is not preserved across an
  1793.   exec() call, hence trying to use setvbuf() before the exec is
  1794.   ineffective.
  1795.  
  1796.   A couple of alternate solutions were proposed by Roger Espel Llima
  1797.   (espel@drakkar.ens.fr):
  1798.  
  1799.   If it's an option, you can use some standalone program that will just
  1800.   run something inside a pty and buffer its input/output.  I've seen a
  1801.   package by the name pty.tar.gz that did that; you could search around
  1802.   for it with archie or AltaVista.
  1803.   Another option (**warning, evil hack**) , if you're on a system that
  1804.   supports this (SunOS, Solaris, Linux ELF do; I don't know about
  1805.   others) is to, on your main program, putenv() the name of a shared
  1806.   executable (*.so)  in LD_PRELOAD, and then in that .so redefine some
  1807.   commonly used libc function that the program you're exec'ing is known
  1808.   to use early.  There you can 'get control' on the running program, and
  1809.   the first time you get it, do a setbuf(stdout, NULL) on the program's
  1810.   behalf, and then call the original libc function with a dlopen() +
  1811.   dlsym().  And you keep the dlsym() value on a static var, so you can
  1812.   just call that the following times.
  1813.  
  1814.   (Editors note:  I still haven't done an expample for how to do pty's,
  1815.   but I hope I will be able to do one after I finish the non-blocking
  1816.   example code.)
  1817.  
  1818.   5.  Writing UDP/SOCK_DGRAM applications
  1819.  
  1820.   5.1.  When should I use UDP instead of TCP?
  1821.  
  1822.   UDP is good for sending messages from one system to another when the
  1823.   order isn't important and you don't need all of the messages to get to
  1824.   the other machine.  This is why I've only used UDP once to write the
  1825.   example code for the faq.  Usually TCP is a better solution.  It saves
  1826.   you having to write code to ensure that messages make it to the
  1827.   desired destination, or to ensure the message ordering.  Keep in mind
  1828.   that every additional line of code you add to your project in another
  1829.   line that could contain a potentially expensive bug.
  1830.  
  1831.   If you find that TCP is too slow for your needs you may be able to get
  1832.   better performance with UDP so long as you are willing to sacrifice
  1833.   message order and/or reliability.
  1834.  
  1835.   UDP must be used to multicast messages to more than one other machine
  1836.   at the same time.  With TCP an application would have to open separate
  1837.   connections to each of the destination machines and send the message
  1838.   once to each target machine.  This limits your application to only
  1839.   communicate with machines that it already knows about.
  1840.  
  1841.   5.2.  What is the difference between "connected" and "unconnected"
  1842.   sockets?
  1843.  
  1844.   From Andrew Gierth (andrew@erlenstar.demon.co.uk):
  1845.  
  1846.   If a UDP socket is unconnected, which is the normal state after a
  1847.   bind() call, then send() or write() are not allowed, since no
  1848.   destination address is available; only sendto() can be used to send
  1849.   data.
  1850.  
  1851.   Calling connect() on the socket simply records the specified address
  1852.   and port number as being the desired communications partner. That
  1853.   means that send() or write() are now allowed; they use the destination
  1854.   address and port given on the connect call as the destination of the
  1855.   packet.
  1856.  
  1857.   5.3.  of the socket?  Does doing a connect() call affect the receive
  1858.   behaviour
  1859.  
  1860.   From Richard Stevens (rstevens@noao.edu):
  1861.  
  1862.   Yes, in two ways.  First, only datagrams from your "connected peer"
  1863.   are returned.  All others arriving at your port are not delivered to
  1864.   you.
  1865.  
  1866.   But most importantly, a UDP socket must be connected to receive ICMP
  1867.   errors.  Pp. 748-749 of "TCP/IP Illustrated, Volume 2" give all the
  1868.   gory details on why this is so.
  1869.  
  1870.   5.4.  How can I read ICMP errors from "connected" UDP sockets?
  1871.  
  1872.   If the target machine discards the message because there is no process
  1873.   reading on the requested port number, it sends an ICMP message to your
  1874.   machine which will cause the next system call on the socket to return
  1875.   ECONNREFUSED.  Since delivery of ICMP messages is not guarenteed you
  1876.   may not recieve this notification on the first transaction.
  1877.  
  1878.   Remember that your socket must be "connected" in order to receive the
  1879.   ICMP errors.  I've been told, and Alan Cox has verified that Linux
  1880.   will return them on "unconnected" sockets.  This may cause porting
  1881.   problems if your application isn't ready for it, so Alan tells me
  1882.   they've added a SO_BSDCOMPAT flag which can be set for Linux kernels
  1883.   after 2.0.0.
  1884.  
  1885.   5.5.  How can I be sure that a UDP message is received?
  1886.  
  1887.   You have to design your protocol to expect a confirmation back from
  1888.   the destination when a message is received.  Of course is the
  1889.   confirmation is sent by UDP, then it too is unreliable and may not
  1890.   make it back to the sender.  If the sender does not get confirmation
  1891.   back by a certain time, it will have to re-transmit the message, maybe
  1892.   more than once.  Now the receiver has a problem because it may have
  1893.   already received the message, so some way of dropping duplicates is
  1894.   required.  Most protocols use a message numbering scheme so that the
  1895.   receiver can tell that it has already processed this message and
  1896.   return another confirmation.  Confirmations will also have to
  1897.   reference the message number so that the sender can tell which message
  1898.   is being confirmed.  Confused?  That's why I stick with TCP.
  1899.  
  1900.   5.6.  How can I be sure that UDP messages are received in order?
  1901.  
  1902.   You can't.  What you can do is make sure that messages are processed
  1903.   in order by using a numbering system as mentioned in ``5.5 How can I
  1904.   be sure that a UDP message is received?''.  If you need your messages
  1905.   to be received and be received in order you should really consider
  1906.   switching to TCP.  It is unlikely that you will be able to do a better
  1907.   job implementing this sort of protocol than the TCP people already
  1908.   have, without a significant investment of time.
  1909.  
  1910.   5.7.  How often should I re-transmit un-acknowleged messages?
  1911.  
  1912.   The simplest thing to do is simply pick a fairly small delay such as
  1913.   one second and stick with it.  The problem is that this can congest
  1914.   your network with useless traffic if there is a problem on the lan or
  1915.   on the other machine, and this added traffic may only serve to make
  1916.   the problem worse.
  1917.  
  1918.   A better technique, described with source code in "UNIX Network
  1919.   Programming" by Richard Stevens (see ``1.5 Where can I get source code
  1920.   for the book [book title]?''), is to use an adaptive timeout with an
  1921.   exponential backoff.  This technique keeps statistical information on
  1922.   the time it is taking messages to reach a host and adjusts timeout
  1923.   values accordingly.  It also doubles the timeout each time it is
  1924.   reached as to not flood the network with useless datagrams.  Richard
  1925.   has been kind enough to post the source code for the book on the web.
  1926.   Check out his home page at http://www.noao.edu/~rstevens.
  1927.  
  1928.   5.8.  How come only the first part of my datagram is getting through?
  1929.  
  1930.   This has to do with the maximum size of a datagram on the two machines
  1931.   involved.  This depends on the sytems involved, and the MTU (Maximum
  1932.   Transmission Unit).  According to "UNIX Network Programming", all
  1933.   TCP/IP implementations must support a minimum IP datagram size of 576
  1934.   bytes, regardless of the MTU.  Assuming a 20 byte IP header and 8 byte
  1935.   UDP header, this leaves 548 bytes as a safe maximum size for UDP
  1936.   messages.  The maximum size is 65516 bytes.  Some platforms support IP
  1937.   fragmentation which will allow datagrams to be broken up (because of
  1938.   MTU values) and then re-assembled on the other end, but not all
  1939.   implementations support this.
  1940.  
  1941.   This information is taken from my reading of "UNIX Netowrk
  1942.   Programming" (see ``1.5 Where can I get source code for the book [book
  1943.   title]?'').
  1944.  
  1945.   Andrew has pointed out the following regarding large UDP messages:
  1946.  
  1947.   Another issue is fragmentation. If a datagram is sent which is too
  1948.   large for the network interface it is sent through, then the sending
  1949.   host will fragment it into smaller packets which are reassembled by
  1950.   the receiving host. Also, if there are intervening routers, then they
  1951.   may also need to fragment the packet(s), which greatly increases the
  1952.   chances of losing one or more fragments (which causes the entire
  1953.   datagram to be dropped).  Thus, large UDP datagrams should be avoided
  1954.   for applications that are likely to operate over routed nets or the
  1955.   Internet proper.
  1956.  
  1957.   5.9.  Why does the socket's buffer fill up sooner than expected?
  1958.  
  1959.   From Paul W. Nelson (nelson@thursby.com):
  1960.  
  1961.   In the traditional BSD socket implementation, sockets that are atomic
  1962.   such as UDP keep received data in lists of mbufs.  An mbuf is a fixed
  1963.   size buffer that is shared by various protocol stacks.  When you set
  1964.   your receive buffer size, the protocol stack keeps track of how many
  1965.   bytes of mbuf space are on the receive buffer, not the number of
  1966.   actual bytes.  This approach is used because the resource you are
  1967.   controlling is really how many mbufs are used, not how many bytes are
  1968.   being held in the socket buffer.  (A socket buffer isn't really a
  1969.   buffer in the traditional sense, but a list of mbufs).
  1970.  
  1971.   For example:  Lets assume your UNIX has a small mbuf size of 256
  1972.   bytes.  If your receive socket buffer is set to 4096, you can fit 16
  1973.   mbufs on the socket buffer.  If you receive 16 UDP packets that are 10
  1974.   bytes each, your socket buffer is full, and you have 160 bytes of
  1975.   data.  If you receive 16 UDP packets that are 200 bytes each, your
  1976.   socket buffer is also full, but contains 3200 bytes of data.  FIONREAD
  1977.   returns the total number of bytes, not the number of messages or bytes
  1978.   of mbufs.  Because of this, it is not a good indicator of how full
  1979.   your receive buffer is.
  1980.  
  1981.   Additionaly, if you receive UDP messages that are 260 bytes, you use
  1982.   up two mbufs, and can only recieve 8 packets before your socket buffer
  1983.   is full. In this case, only 2080 bytes of the 4096 are held in the
  1984.   socket buffer.
  1985.  
  1986.   This example is greatly simplified, and the real socket buffer
  1987.   algorithm also takes into account some other parameters.  Note that
  1988.   some older socket implementations use a 128 byte mbuf.
  1989.  
  1990.   6.  Sample Source Code
  1991.  
  1992.   The sample source code is no longer included in the faq.  To get it,
  1993.   please download it from one of the unix-socket-faq www pages:
  1994.  
  1995.        http://www.auroraonline.com/sock-faq
  1996.        http://kipper.york.ac.uk/~vic/sock-faq
  1997.  
  1998.   If you don't have web access, you can ftp it with ftpmail by following
  1999.   the following instructions.  Please do not use the ftp server if you
  2000.   have access to the web, since computain.com is connected only by a
  2001.   28.8 modem, and you'd be amazed how much traffic this faq generates.
  2002.  
  2003.   To get the sample source by mail, send mail to ftpmail@decwrl.dec.com,
  2004.   with no subject line and a body like this:
  2005.  
  2006.          reply <put your email address here>
  2007.          connect ftp.computain.com
  2008.          binary
  2009.          uuencode
  2010.          get pub/sockets/examples.tar.gz
  2011.          quit
  2012.  
  2013.   Save the reply as examples.uu, and type:
  2014.  
  2015.          % uudecode examples.uu
  2016.          % gunzip examples.tar.gz
  2017.          % tar xf examples.tar
  2018.  
  2019.   This will create a directory called socket-faq-examples which contains
  2020.   the sample code from this faq, plus a sample client and server for
  2021.   both tcp and udp.
  2022.  
  2023.   Note that this package requires the gnu unzip program to be installed
  2024.   on your system.  It is very common, but if you don't have it you can
  2025.   get the source for it from:
  2026.  
  2027.        ftp://prep.ai.mit.edu/pub/gnu/gzip-1.2.4.tar
  2028.  
  2029.   If you don't have ftp access, you can obtain it in a way similar to
  2030.   obtaining the sample source.  I'll leave the exact changes to the body
  2031.   of the message as an excersise for the reader.
  2032.  
  2033.