home *** CD-ROM | disk | FTP | other *** search
/ ftp.pasteur.org/FAQ/ / ftp-pasteur-org-FAQ.zip / FAQ / unix-faq / socket next >
Text File  |  1998-03-23  |  96KB  |  2,174 lines

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