4sn3z

Socket Client2

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