Advertisement
Guest User

simple tcp client

a guest
Sep 9th, 2011
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.97 KB | None | 0 0
  1.  
  2.  /*
  3.  * Most of the code is from http://www.paulgriffiths.net/program/c/srcs/echoclntsrc.html
  4.  *
  5.  */
  6.  
  7. /* Just included everything possible .. dont think it makes a difference to the code */
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <stdarg.h>
  11. #include <errno.h>
  12. #include <sys/types.h>
  13. #include <sys/socket.h>
  14. #include <netinet/in.h>
  15. #include <syslog.h>
  16. #include <netdb.h>
  17. #include <string.h>
  18. #include <ctype.h>
  19. #include <pwd.h>
  20. #include <regex.h>
  21. #include <sys/time.h>
  22. #include  <signal.h>
  23. #include <unistd.h>
  24. #include <arpa/inet.h>
  25. #define BOUNCEHOST "127.0.0.1"
  26. #define BOUNCEPORT   1601
  27. #define MAX_LINE 1000
  28.  
  29.  
  30.  
  31. /*  Write a line to a socket  */
  32. ssize_t Writeline(int sockd, const void *vptr, size_t n) {
  33.   size_t      nleft;
  34.   ssize_t     nwritten;
  35.   const char *buffer;
  36.  
  37.   buffer = vptr;
  38.   nleft  = n;
  39.  
  40.  
  41.  while ( nleft > 0 ) {
  42.     if ( (nwritten = write(sockd, buffer, nleft)) <= 0 ) {
  43.       if ( errno == EINTR )
  44.         nwritten = 0;
  45.       else
  46.         return -1;
  47.     }
  48.     nleft  -= nwritten;
  49.     buffer += nwritten;
  50.   }
  51.  
  52.   return n;
  53. }
  54.  
  55.  
  56.  
  57.  
  58.  
  59.  
  60.  
  61. int main(int argc, char* argv[]) {
  62.   int       conn_s;
  63.   struct    sockaddr_in servaddr;
  64.   char      buffer[MAX_LINE];
  65.  
  66.   if (argc != 3) {
  67.     fprintf(stderr, "Incorrect usage\n");
  68.     exit(1);
  69.   }
  70.   if ( (conn_s = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) {
  71.     fprintf(stderr, "ECHOCLNT: Error creating listening socket.\n");
  72.     exit(EXIT_FAILURE);
  73.   }
  74.   memset(&servaddr, 0, sizeof(servaddr));
  75.   servaddr.sin_family      = AF_INET;
  76.   servaddr.sin_port        = htons(BOUNCEPORT);
  77.   if ( inet_aton(BOUNCEHOST, &servaddr.sin_addr) <= 0 ) {
  78.     printf("ECHOCLNT: Invalid remote IP address.\n");
  79.     exit(EXIT_FAILURE);
  80.   }
  81.   if ( connect(conn_s, (struct sockaddr *) &servaddr, sizeof(servaddr) ) < 0 ) {
  82.     printf("ECHOCLNT: Error calling connect()\n");
  83.     exit(EXIT_FAILURE);
  84.   }
  85.   while(fgets(buffer,MAX_LINE,stdin)) Writeline(conn_s, buffer, strlen(buffer));
  86.  
  87.   exit(0);
  88.  
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement