client.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <arpa/inet.h>
  6. #include <fcntl.h>
  7. #include <errno.h>
  8. #define PORT 8081
  9. #define SERVER_IP "127.0.0.1"
  10. int main() {
  11. int sockfd;
  12. struct sockaddr_in server_address;
  13. if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
  14. perror("Socket creation failed");
  15. exit(EXIT_FAILURE);
  16. }
  17. printf("enter into program\n");
  18. server_address.sin_family = AF_INET;
  19. server_address.sin_port = htons(PORT);
  20. inet_pton(AF_INET, SERVER_IP, &server_address.sin_addr);
  21. if (connect(sockfd, (struct sockaddr*)&server_address, sizeof(server_address)) < 0) {
  22. perror("Connection failed");
  23. close(sockfd);
  24. exit(EXIT_FAILURE);
  25. }
  26. char s[]="data.txt";
  27. send(sockfd,s,strlen(s),0);
  28. char buffer[20];
  29. int bytes_read;
  30. FILE* fp = fopen("receiver.txt","w");
  31. if(fp == NULL)
  32. printf("file doesn't open\n");
  33. else
  34. printf("file open successfully\n");
  35. while((bytes_read = recv(sockfd,buffer,sizeof(buffer),0)) > 0)
  36. {
  37. fwrite(buffer,1,bytes_read,fp);
  38. }
  39. if(bytes_read < 0)
  40. perror("read failed\n");
  41. close(sockfd);
  42. fclose(fp);
  43. }