HPlogo Berkeley Sockets/iX Reference Manual: HP 3000 MPE/iX Computer Systems > Chapter 5 Programming Example

Source Program

» 

Technical documentation

Complete book in PDF
» Feedback

 » Table of Contents

The following program was broken into steps to show how a connection is established between two sockets.

  1. Establish the connection in loopback, using a single process:

       #include </stdio.h>
    
       #include <sys/types.h>
    
       #include <sys/socket.h>
    
       #include <sys/stat.h>
    
       #include <sys/in.h>
    
       #include <sys/errno.h>
    
       #include <fcntl.h>
    
       #include <unistd.h>
    
    
    
       main()
    
       {
    
          int sock;
    
          int peer1;
    
          int struc_len;
    
          int fret;
    
          int sock2;
    
          struct sockaddr_in sockaddr;
    
  2. Create the two sockets:

       sock=socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
    
       if (sock == -1) 
    
          print ("Error creating socket.\n");
    
    
    
       peer1 = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
    
       if (peer1 == -1) 
    
          printf ("Error creating socket.\n");
    
  3. Create the socket structure to bind the socket. The IP address used is 0 (loopback), and the SAP is set to an arbitrary constant (4444). This structure is used for both the bind and the connect:

       sockaddr.sin_family = AF_INET;
    
       sockaddr.sin_addr.s_addr = INADDR_THISHOST;
    
       sockaddr.sin_port = 4444;
    
       
    
       struc_len = 16;
    
       
    
       if (bind (sock, (struct sockaddr *)&sockaddr,
    
                sizeof (sockaddr)) < 0 ) 
    
          printf ("Bind failed\n);
    
       listen (sock,10);
    

  4. Set the socket initiating the connection to be nonblocking. This allows the connect to return to the user without blocking and waiting for accept:

    NOTE: The sfcntl function should be used until the fcntl is provided by the operating system.
       sfcntl (peer1, F_SETFL, O_NONBLOCK);
    
    
    
       fret = connect (peer1, (struct sockaddr *) &sockaddr, struc_len);
    
       if (fret == -1)
    
          printf ("Connect failed with error %d\n",errno);
    
       else 
    
          printf ("Connect succeeded\n");
    
    
    
       sock2 = accept (sock, (struct sockaddr *) &sockaddr, &struc_len);
    
       if (sock2 == -1)
    
          printf ("Accept failed\n");
    
       else
    
          printf ("Accept succeeded\n");
    
  5. Call recv to complete the connection:

       recv (peer1, 0,0,0);
    
       }   /* end main */
Feedback to webmaster