Advertisement
Guest User

Untitled

a guest
Apr 11th, 2021
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <netdb.h>
  3. #include <netinet/in.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <sys/socket.h>
  7. #include <sys/types.h>
  8. #define MAX 80
  9. #define PORT 8080
  10. #define SA struct sockaddr
  11.  
  12. int func(int sockfd){
  13. char recvBuff[20];
  14. int n;
  15. write(sockfd,"Hello, my name is lambda. Who are you?\n",39);
  16. //FILE * f = fopen("log3.txt","a+");
  17. /*
  18. n = recv(sockfd, recvBuff, 20,0);
  19. if (n<0)
  20. return 0;
  21. //printf("%d\n",strcmp(recvBuff,"ha"));
  22. FILE * f = fopen("log3.txt","a+");
  23. fputs(recvBuff,f);
  24. fclose(f);
  25. if (strcmp(recvBuff,"ha\n")!=0){
  26. write(sockfd,"Oh, sorry, no...\n",17);
  27. return 0;
  28. }
  29. write(sockfd,"Ready\n",6);*/
  30. n = recv(sockfd, recvBuff, 200,0);
  31. //fputs(recvBuff,f);
  32. //fclose(f);
  33. printf("%d\n",n);
  34. }
  35. int main()
  36. {
  37. int sockfd, connfd, len;
  38. struct sockaddr_in servaddr, cli;
  39.  
  40. // socket create and verification
  41. sockfd = socket(AF_INET, SOCK_STREAM, 0);
  42. setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int));
  43. if (sockfd == -1) {
  44. printf("socket creation failed...\n");
  45. exit(0);
  46. }
  47. else
  48. printf("Socket successfully created..\n");
  49. bzero(&servaddr, sizeof(servaddr));
  50.  
  51. // assign IP, PORT
  52. servaddr.sin_family = AF_INET;
  53. servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
  54. servaddr.sin_port = htons(31337);
  55.  
  56. // Binding newly created socket to given IP and verification
  57. if ((bind(sockfd, (SA*)&servaddr, sizeof(servaddr))) != 0) {
  58. printf("socket bind failed...\n");
  59. exit(0);
  60. }
  61. else
  62. printf("Socket successfully binded..\n");
  63.  
  64. // Now server is ready to listen and verification
  65. if ((listen(sockfd, 5)) != 0) {
  66. printf("Listen failed...\n");
  67. exit(0);
  68. }
  69. else
  70. printf("Server listening..\n");
  71. len = sizeof(cli);
  72.  
  73. // Accept the data packet from client and verification
  74. while (1){
  75. connfd = accept(sockfd, (SA*)&cli, &len);
  76.  
  77. if (connfd < 0) {
  78. printf("server acccept failed...\n");
  79. exit(0);
  80. }
  81. else
  82. printf("server acccept the client...\n");
  83.  
  84. if (fork() ==0){
  85. func(connfd);
  86. close(connfd);
  87. }
  88. }
  89. close(sockfd);
  90. }
  91.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement