server.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<unistd.h>
  4. #include<fcntl.h>
  5. #include<arpa/inet.h>
  6. #define PORT 8081
  7. void send_file(int fd,char* filename)
  8. {
  9. int fp = open(filename,O_RDONLY);
  10. printf("file:%s",filename);
  11. if(fp < 0)
  12. {
  13. printf("file doesn't open\n");
  14. return ;
  15. }
  16. char buffer[1024];
  17. int bytes_read;
  18. while((bytes_read = read(fp,buffer,sizeof(buffer)))>0)
  19. {
  20. if((send(fd,buffer,bytes_read,0))<0)
  21. {
  22. perror("send data failed\n");
  23. break;
  24. }
  25. }
  26. close(fp);
  27. return;
  28. }
  29. int main()
  30. {
  31. int sockfd,new_socket;
  32. struct sockaddr_in address;
  33. if((sockfd = socket(AF_INET,SOCK_STREAM,0))<0)
  34. perror("socket creation failed\n");
  35. address.sin_family = AF_INET;
  36. address.sin_port = htons(PORT);
  37. address.sin_addr.s_addr = INADDR_ANY;
  38. if((bind(sockfd,(struct sockaddr*)&address,sizeof(address)))<0)
  39. perror("bind failed\n");
  40. if((listen(sockfd,3))<0)
  41. perror("server listening failed\n");
  42. else
  43. printf("server listening\n");
  44. int addrlen =sizeof(address);
  45. while((new_socket = accept(sockfd, (struct sockaddr *)&address, (socklen_t*)&addrlen))) {
  46. printf("connected to client\n");
  47. char s[20];
  48. int read_data;
  49. read_data = read(new_socket,s,sizeof(s)-1);
  50. s[read_data]='\0';
  51. printf("which file we want to read\n");
  52. send_file(new_socket,s);
  53. printf("file sent to client\n");
  54. close(new_socket);
  55. }
  56. close(sockfd);
  57. }