Advertisement
Guest User

Untitled

a guest
Nov 27th, 2014
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. #include<stdlib.h>
  2. #include<stdio.h>
  3. #include<sys/types.h>
  4. #include<sys/socket.h>
  5. #include<netinet/in.h>
  6. #include<string.h>
  7. #include<pthread.h>
  8.  
  9. void* serve_request(void* newsockfdptr)
  10. {
  11. printf("Thread started\n");
  12. char buffer[256];
  13. int n;
  14.  
  15. int newsockfd=*((int*)newsockfdptr);
  16.  
  17. /*if connection established then start communicating*/
  18. bzero(buffer, 256);
  19. n=read(newsockfd, buffer, 255);
  20. if(n<0)
  21. {
  22. perror("Error reading from socket");
  23. }
  24. printf("Here is the message: %s\n",buffer);
  25.  
  26. /*write response to the client*/
  27. n=write(newsockfd,"I got your message", 18);
  28. if(n<0)
  29. {
  30. perror("Error writing to socket");
  31. exit(1);
  32. }
  33. close(newsockfd);
  34. printf("Thread ended\n");
  35. }
  36.  
  37. int main(int argc, char* argv)
  38. {
  39. pid_t pid;
  40.  
  41. pid=fork();
  42. if(pid!=0)
  43. exit(0);
  44.  
  45. int sockfd, newsockfd, portno, clilen;
  46. char buffer[256];
  47. struct sockaddr_in serv_addr, cli_addr;
  48. int n;
  49. pthread_t temp;
  50.  
  51. /*first call to socket function*/
  52. sockfd=socket(AF_INET, SOCK_STREAM, 0);
  53. setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, 0, 0);
  54. if(sockfd<0)
  55. {
  56. perror("Error opening socket");
  57. exit(1);
  58. }
  59.  
  60. /*initialize socket structure*/
  61. bzero((char*)&serv_addr, sizeof(serv_addr));
  62. portno=5001;
  63. serv_addr.sin_family=AF_INET;
  64. serv_addr.sin_addr.s_addr=INADDR_ANY;
  65. serv_addr.sin_port=htons(portno);
  66.  
  67. /*now bind the host address using bind() call.*/
  68. if(bind(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr))<0)
  69. {
  70. perror("Error on binding");
  71. exit(1);
  72. }
  73.  
  74. /*now start listening for the clients, here process will
  75. go in sleep mode and will wait for the incoming connection*/
  76. listen(sockfd, 5);
  77. clilen=sizeof(cli_addr);
  78.  
  79. while(1)
  80. {
  81. /*accept actual connection from the client*/
  82. newsockfd=accept(sockfd, (struct sockaddr*)&cli_addr, &clilen);
  83. if(newsockfd<0)
  84. {
  85. perror("Error on accept");
  86. exit(1);
  87. }
  88. pthread_create(&temp,NULL,serve_request, &newsockfd);
  89. //serve_request(newsockfd);
  90. }
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement