crseat

sockets

Jan 23rd, 2012
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 8.49 KB | None | 0 0
  1. include <stdio.h>
  2. include <stdlib.h>
  3. include <string.h>
  4. include <sys/types.h>
  5. include <sys/socket.h>
  6. include <sys/time.h>
  7. include <unistd.h> /* for gethostname() */
  8. include <arpa/inet.h> /* for IP address structures and functions */
  9. include <netdb.h> /* for gethostbyname() */
  10. int main(int argc, char argv[], char *envp[]) { int msgsock; / The data socket for the client / struct sockaddr_in name; struct hostent *hp; / Used to resolve hostname to IP address */ char chrline[80]; int i, ret, length;
  11. /* We must give the hostname and portnumber on the command line. This * checks that the user has typed both. */
  12. if (argc < 3)
  13. {
  14.     printf("error: Invoke this program via: \n");
  15.     printf("       vcsend <hostname> <portnumber> \n");
  16.     return (-1);
  17. }
  18. /* Since we are allowing a domain name as the hostname, we must call * gethostbyname() to convert the hostname into an IP address. */
  19. hp = gethostbyname(argv[1]);
  20. if (hp == NULL)
  21. {
  22.     printf("sender: gethostbyname() failed.\n");
  23.     printf("        Are you sure the hostname is correct? \n");
  24.     return (-1);
  25. }
  26. printf("\nsender: hostname has been resolved.\n");
  27. /* Copy the resolved IP address over into the name structure along with * the portnumber given on the command line */ memcpy((char *)&name.sin_addr, (char *)hp->h_addr, hp->h_length); name.sin_family = AF_INET; name.sin_port = htons((short)atoi(argv[2]));
  28. /* Allocate the data socket and attempt to connect to vcrec. Exit the * program if either socket() or connect() fails. */
  29. printf("sender: Attempting to connect to server.\n");
  30. msgsock = socket(AF_INET, SOCK_STREAM, 0);
  31. if (msgsock < 0)
  32. {
  33.     perror("sender: socket() failed. ");
  34.     return (-1);
  35. }
  36.  
  37. ret = connect(msgsock, (struct sockaddr *)&name, sizeof name);
  38. if (ret != 0)
  39. {
  40.     perror("sender: connect() failed. ");
  41.     fprintf(stderr,
  42.     "\n        are you sure that the portnumber is correct? \n");
  43.     fflush(stderr);
  44.     return (-1);
  45. }
  46. /* Wait for the handshake from vcrec before continuing */
  47. printf("sender: Waiting for handshake from vcrec...\n");
  48. sleep(1);   /* pause for clean screen display */
  49. fflush(stdout);
  50. recv(msgsock, chrline, sizeof(chrline) - 1, 0); /* Handshake character */
  51. printf("sender: Handshake received. Entering data loop.\n");
  52.  
  53. printf("\nEnter a line of characters at the prompt.\n");
  54. printf("To exit the program, type just a period and hit enter.\n");
  55. /* Go into an infinite loop. We'll use the "break" statement to exit * the loop if the user types a period or send() fails */
  56. while(1) { printf("enter line> ");
  57. /* Read input from user */
  58.   fgets(chrline, sizeof(chrline) - 1, stdin);
  59. /* Check for the period to end the connection and also convert any
  60.  * newlines into null characters */
  61.   for (i = 0 ; i < (sizeof(chrline) - 1) ; i++)
  62.     {
  63.       if ( (chrline[i] == '\n') || (chrline[i] == '\0') )
  64.           break;
  65.     }
  66.   if (chrline[i] == '\n')
  67.       chrline[i] = '\0';    /* get rid of newline */
  68.  
  69.   length = strlen(chrline);
  70.   if (chrline[0] == '.')        /* end of stream */
  71.     {
  72.       printf("sender: termination requested \n");
  73.       break; /* Exit out of loop */
  74.     }
  75.  
  76.   ret = send(msgsock, chrline, length + 1, 0);
  77.  
  78.   if (ret < 0)
  79. {
  80.       perror("sender: write() failed. ");
  81.   break;  /* Exit out of loop */
  82. }
  83. }
  84. /* Closing the data socket from vcsend will trigger recv() on vcrec to * return 0, which will also cause vcrec to close its sockets and exit */ close(msgsock);
  85. return (0);
  86. } /* end of main */
  87.  
  88. RECEIVE:
  89. include <stdio.h>
  90. include <stdlib.h>
  91. include <string.h>
  92. include <sys/types.h>
  93. include <sys/socket.h>
  94. include <sys/time.h>
  95. include <unistd.h> /* for gethostname() */
  96. include <arpa/inet.h> /* for IP address structures and functions */
  97. include <netdb.h>
  98. int main(int argc, char argv[], char *envp[]) { int sock, msgsock; / Sockets are integer file descriptors on Linux */ struct sockaddr_in name, caller; char buf[2048]; int size, length, ret, k;
  99. /* Process the command line for the buffer size, if given / if (argc > 1) { size = atoi(argv[1]); / Validate that the given argument is between 1 and sizeof(buf) - 1 * Set to the default size if argument is invalid / if (size < 1 || size > sizeof(buf) - 1) size = sizeof(buf) - 1; } else { size = sizeof(buf) - 1; / Default size */ }
  100. /* Create the listen socket. This is a TCP socket, so use SOCK_STREAM * Exit if the socket cannot be created */ sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) { perror("receiver: socket() failed. "); return (-1); }
  101. /* Bind the socket to an IP address and port. We will use the IP address * INADDR_ANY, which tells the system to assign the IP address, and the * port number 0, which tells the system to assign a random port number. * * First we have to set the fields in the sockaddr_in object "name" and then * we can call bind(). Again, exit if bind() fails. */
  102. name.sin_family = AF_INET;         /* TCP/IP family */
  103.  
  104. name.sin_addr.s_addr = INADDR_ANY; /* INADDR_ANY = assigned by system */
  105.  
  106. name.sin_port = htons(0);            /* 0 = assigned by system */
  107.  
  108. ret = bind(sock,(struct sockaddr *)&name,sizeof name);
  109. if (ret < 0)
  110. {
  111.     perror("receiver: bind() failed. ");
  112.     return (-1);
  113. }
  114. /* In order to use vcsend to send data to this program, we need to know * what port number the system just assigned this program. So this segment * calls getsockname() to update the sockaddr_in object "name" with the * system assigned values and then print that info to the screen. */
  115. length = sizeof name;
  116. ret = getsockname(sock, (struct sockaddr *)&name, (socklen_t *)&length);
  117. if (ret < 0)
  118. {
  119.     perror("receiver: getsockname() failed. ");
  120.     return (-1);
  121. }
  122.  
  123. sleep(1);   /* pause for clean screen display */
  124.  
  125. printf("\nreceiver: process id: %d ", (int)getpid());
  126. printf("\nreceiver: IP address: %d.%d.%d.%d",
  127.     (ntohl(name.sin_addr.s_addr) & 0xff000000) >> 24,
  128.     (ntohl(name.sin_addr.s_addr) & 0x00ff0000) >> 16,
  129.     (ntohl(name.sin_addr.s_addr) & 0x0000ff00) >>  8,
  130.     (ntohl(name.sin_addr.s_addr) & 0x000000ff));
  131. printf("\nreceiver: port number: %hu", ntohs(name.sin_port));
  132. printf("\n");
  133. fflush(stdout);
  134. /* Now we will call listen() and wait for a client to connect. The * accept() function will block until there is a client or an error. */
  135. listen(sock,5);     /* up to 5 clients can connect. only 1st is accepted */
  136. k = sizeof caller;
  137. msgsock = accept(sock, (struct sockaddr *)&caller, (socklen_t *)&k);
  138. /* We only reach this point when there is an error or a client. We can * check the value of msgsock (the data socket) to see which has happened */
  139. if (msgsock == -1)
  140. {
  141.     perror("receiver: accept() failed. ");
  142. }
  143. else
  144. { printf("\nreceiver: Valid connection received.\n"); printf("receiver: Sending handshake.\n"); fflush(stdout);
  145.     /* let vcsend know we are ready by sending a single character */
  146.   buf[0]= '0';      
  147.   send(msgsock, buf, 1, 0);
  148.  
  149. printf("receiver: Waiting for client....\n");
  150.  
  151.   do    {
  152.         bzero(buf,sizeof buf);  /* zero buffer to remove old data */
  153.  
  154.   /* recv() will block until the client sends information, the client
  155.    * closes the connection or an error occurs on the data socket. */
  156.         ret = recv(msgsock, buf, size, 0);
  157.         if (ret < 0)
  158.         {
  159.             perror("receiver: recv() failed. ");
  160.         }
  161.         if (ret == 0)
  162.         {
  163.         printf("        received-->sender has ended connection \n");
  164.         }
  165.         else
  166.         {
  167.             printf("        received-->%s \n",buf);
  168.         }
  169.         printf("enter line> ");
  170.  
  171. /* Read input from user */
  172.   fgets(chrline, sizeof(chrline) - 1, stdin);
  173. /* Check for the period to end the connection and also convert any
  174.  * newlines into null characters */
  175.   for (i = 0 ; i < (sizeof(chrline) - 1) ; i++)
  176.     {
  177.       if ( (chrline[i] == '\n') || (chrline[i] == '\0') )
  178.           break;
  179.     }
  180.   if (chrline[i] == '\n')
  181.       chrline[i] = '\0';    /* get rid of newline */
  182.  
  183.   length = strlen(chrline);
  184.   if (chrline[0] == '.')        /* end of stream */
  185.     {
  186.       printf("sender: termination requested \n");
  187.       break; /* Exit out of loop */
  188.     }
  189.  
  190.   ret = send(msgsock, chrline, length + 1, 0);
  191.  
  192.   if (ret < 0)
  193. {
  194.       perror("sender: write() failed. ");
  195.   break;  /* Exit out of loop */
  196. }
  197.     } while (ret != 0); /* Exit loop only when client ends connection */
  198. }
  199. /* When we exit the recv() loop, the client has ended the connection, so * all that remains is closing the sockets. */
  200. printf("receiver: ending session also and exiting. \n");
  201. close(msgsock);     /* close data socket */
  202. close(sock);      /* close listen socket */
  203.  
  204. return (0);
  205. } /* end of main */
Advertisement
Add Comment
Please, Sign In to add comment