Advertisement
danielhilst

hwtcpcli.c

Apr 22nd, 2014
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.62 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <sys/types.h>
  3. #include <sys/socket.h>
  4. #include <string.h>
  5. #include <stdlib.h>
  6. #include <netinet/in.h>
  7.  
  8. #define pexit(x)                                \
  9.         do {                                    \
  10.                 perror(x);                      \
  11.                 exit(EXIT_FAILURE);             \
  12.         } while (0)
  13.  
  14. #define BSIZ 1024
  15. static char buffer[BSIZ];
  16.  
  17. static struct sockaddr_in saddr;
  18.  
  19. int main(int argc, char **argv)
  20. {
  21.         int sock, clisock, n = 3;
  22.         char *str = "hello world";
  23.  
  24.         sock = socket(AF_INET, SOCK_STREAM, 0);
  25.        
  26.         memset(&saddr, '\0', sizeof(saddr));
  27.         saddr.sin_family = AF_INET;
  28.         saddr.sin_port = htons(atoi(argv[2]));
  29.  
  30.         if (argc < 2) {
  31.                 fprintf(stderr, "usage: %s ADDR PORT\n", argv[0]);
  32.                 exit(EXIT_FAILURE);
  33.  
  34.         }
  35.  
  36.         if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(int)))
  37.                 pexit("setsockopt");
  38.  
  39.         if (!inet_aton(argv[1], &saddr.sin_addr.s_addr))
  40.                 pexit("inet_aton");
  41.  
  42.         /* if (bind(sock, (struct sockaddr *)&saddr, sizeof(saddr))) */
  43.         /*         pexit("bind"); */
  44.         /* puts("bind OK"); */
  45.  
  46.         if (connect(sock, (struct sockaddr *)&saddr, sizeof(saddr)))
  47.                 pexit("connect");
  48.         puts("connect OK");
  49.  
  50.         for (;;) {
  51.                 n = recv(sock, buffer, BSIZ, MSG_DONTWAIT);
  52.  
  53.                 if (n > 0) {
  54.                         printf("'%.*s'\n", n, buffer);
  55.                         buffer[n-1] = '@';
  56.                         send(sock, buffer, n, MSG_DONTWAIT);
  57.                 }
  58.         }
  59.  
  60.         return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement