Advertisement
anta40

tcpclient

Apr 5th, 2011
328
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.84 KB | None | 0 0
  1. /* tcpclient.c */
  2.  
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <stdlib.h>
  6. #include <unistd.h>
  7. #include <errno.h>
  8.  
  9. #ifdef __WIN32
  10.     #include <winsock.h>
  11.     #define bzero(b,len) (memset((b), '\0', (len)), (void) 0)
  12. #else
  13.     #include <sys/socket.h>
  14.     #include <sys/types.h>
  15.     #include <netinet/in.h>
  16.     #include <netdb.h>
  17. #endif
  18.  
  19.  
  20. int main()
  21.  
  22. {
  23.  
  24.         int sock, bytes_recieved;  
  25.         char send_data[1024],recv_data[1024];
  26.         struct hostent *host;
  27.         struct sockaddr_in server_addr;  
  28.  
  29.         host = gethostbyname("127.0.0.1");
  30.  
  31.         if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
  32.             perror("Socket");
  33.             exit(1);
  34.         }
  35.  
  36.         server_addr.sin_family = AF_INET;    
  37.         server_addr.sin_port = htons(5000);  
  38.         server_addr.sin_addr = *((struct in_addr *)host->h_addr);
  39.         bzero(&(server_addr.sin_zero),8);
  40.  
  41.         if (connect(sock, (struct sockaddr *)&server_addr,
  42.                     sizeof(struct sockaddr)) == -1)
  43.         {
  44.             perror("Connect");
  45.             exit(1);
  46.         }
  47.  
  48.         while(1)
  49.         {
  50.        
  51.           bytes_recieved=recv(sock,recv_data,1024,0);
  52.           recv_data[bytes_recieved] = '\0';
  53.  
  54.           if (strcmp(recv_data , "q") == 0 || strcmp(recv_data , "Q") == 0)
  55.           {
  56.            close(sock);
  57.            break;
  58.           }
  59.  
  60.           else
  61.            printf("\nRecieved data = %s " , recv_data);
  62.            
  63.            printf("\nSEND (q or Q to quit) : ");
  64.            gets(send_data);
  65.            
  66.           if (strcmp(send_data , "q") != 0 && strcmp(send_data , "Q") != 0)
  67.            send(sock,send_data,strlen(send_data), 0);
  68.  
  69.           else
  70.           {
  71.            send(sock,send_data,strlen(send_data), 0);  
  72.            close(sock);
  73.            break;
  74.           }
  75.        
  76.         }  
  77. return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement