zero_shubham1

tcp-client

Jan 20th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.52 KB | None | 0 0
  1. // Write CPP code here
  2. #include <netdb.h>
  3. #include <stdio.h>
  4. #include <unistd.h>
  5. #include <netinet/in.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <sys/socket.h>
  9. #include <sys/types.h>
  10. #include <arpa/inet.h>
  11. #define MAX 80
  12. #define PORT 8080
  13. #define SA struct sockaddr
  14. void func(int sockfd)
  15. {
  16.     char buff[MAX];
  17.     int n;
  18.     for (;;) {
  19.         bzero(buff, sizeof(buff));
  20.         printf("Enter the string : ");
  21.         n = 0;
  22.         while ((buff[n++] = getchar()) != '\n')
  23.             ;
  24.         write(sockfd, buff, sizeof(buff));
  25.         bzero(buff, sizeof(buff));
  26.         read(sockfd, buff, sizeof(buff));
  27.         printf("From Server : %s", buff);
  28.         if ((strncmp(buff, "exit", 4)) == 0) {
  29.             printf("Client Exit...\n");
  30.             break;
  31.         }
  32.     }
  33. }
  34.  
  35. int main()
  36. {
  37.     int sockfd, connfd;
  38.     struct sockaddr_in servaddr, cli;
  39.  
  40.     // socket create and varification
  41.     sockfd = socket(AF_INET, SOCK_STREAM, 0);
  42.     if (sockfd == -1) {
  43.         printf("socket creation failed...\n");
  44.         exit(0);
  45.     }
  46.     else
  47.         printf("Socket successfully created..\n");
  48.     bzero(&servaddr, sizeof(servaddr));
  49.  
  50.     // assign IP, PORT
  51.     servaddr.sin_family = AF_INET;
  52.     servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
  53.     servaddr.sin_port = htons(PORT);
  54.  
  55.     // connect the client socket to server socket
  56.     if (connect(sockfd, (SA*)&servaddr, sizeof(servaddr)) != 0) {
  57.         printf("connection with the server failed...\n");
  58.         exit(0);
  59.     }
  60.     else
  61.         printf("connected to the server..\n");
  62.  
  63.     // function for chat
  64.     func(sockfd);
  65.  
  66.     // close the socket
  67.     close(sockfd);
  68. }
Add Comment
Please, Sign In to add comment