C   111

client4

Guest on 25th August 2022 01:58:49 PM

  1. /*  Make the necessary includes and set up the variables.  */
  2.  
  3. #include <stdlib.h>
  4. #include <sys/types.h>
  5. #include <sys/socket.h>
  6. #include <stdio.h>
  7. #include <netinet/in.h>
  8. #include <arpa/inet.h>
  9. #include <unistd.h>
  10.  
  11. int main(int argc, char *argv[])
  12. {
  13.     int sockfd;
  14.     int len;
  15.     struct sockaddr_in address;
  16.     int result;
  17.     char ch = 'R';
  18.  
  19.     if(argc<3)
  20.       {
  21.         printf("\nPlease type:");
  22.         printf("\n      client4 <IP address> <port>");
  23.         printf("\n e.g. client4 192.168.25.12 34222\n\n");
  24.         return -1;
  25.       }
  26.  
  27.  
  28. /*  Create a socket for the client.  */
  29.  
  30.     sockfd = socket(AF_INET, SOCK_STREAM, 0);
  31.  
  32. /*  Name the socket, as agreed with the server.  */
  33.  
  34.     address.sin_family = AF_INET;
  35.     address.sin_addr.s_addr = inet_addr(argv[1]);
  36.     address.sin_port = htons(atoi(argv[2]));
  37.     len = sizeof(address);
  38.  
  39. /*  Now connect our socket to the server's socket.  */
  40.  
  41.     result = connect(sockfd, (struct sockaddr *)&address, len);
  42.  
  43.     if(result == -1) {
  44.         perror("oops: client4");
  45.         exit(1);
  46.     }
  47.  
  48. /*  We can now read/write via sockfd.  */
  49.  
  50.     write(sockfd, &ch, 1);
  51.     read(sockfd, &ch, 1);
  52.     printf("char from server = %c\n", ch);
  53.     close(sockfd);
  54.     exit(0);
  55. }

Raw Paste


Login or Register to edit or fork this paste. It's free.