Advertisement
Guest User

server.c

a guest
Sep 21st, 2016
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <sys/socket.h>
  5. #include <netinet/in.h>
  6.  
  7.  
  8. int main() {
  9. int def_sock, new_sock;
  10. struct sockaddr_in s_addr;
  11. struct sockaddr_in n_addr;
  12. socklen_t addr_size;
  13. char buffer[1024];
  14.  
  15. /*---- Create the socket. The three arguments are: ----*/
  16. /* 1) Internet domain 2) Stream socket 3) Default protocol (TCP in this case) */
  17. def_sock = socket(AF_INET, SOCK_STREAM, 0);
  18.  
  19. if (def_sock == -1) {
  20. printf("Socket can't be created, exit script");
  21. exit(1);
  22. }
  23.  
  24.  
  25. /*---- Configure settings of the server address struct ----*/
  26. s_addr.sin_family = AF_INET;
  27. s_addr.sin_port = htons(5001);
  28. s_addr.sin_addr.s_addr = INADDR_ANY;
  29.  
  30. memset(s_addr.sin_zero, '\0', sizeof s_addr.sin_zero);
  31. printf("Port = '%d'\n", s_addr.sin_port);
  32.  
  33. /*---- Bind the address struct to the socket ----*/
  34. bind(def_sock, (struct sockaddr *) &s_addr, sizeof(s_addr));
  35.  
  36.  
  37.  
  38. /*---- Listen on the socket, with 5 max connection requests queued ----*/
  39. if(listen(def_sock,5)==0)
  40. printf("Listening\n");
  41. else
  42. printf("Listening can't be started\n");
  43.  
  44.  
  45. /*---- Accept call creates a new socket for the incoming connection ----*/
  46. do {
  47. addr_size = sizeof n_addr;
  48. new_sock = accept(def_sock, (struct sockaddr *) &n_addr, &addr_size);
  49.  
  50. if ( new_sock == -1 ) {
  51. printf("Can't create socket for connection\n");
  52. exit(1);
  53. }
  54.  
  55. /*---- Send message to the socket of the incoming connection ----*/
  56. memset(buffer, 0, sizeof buffer);
  57. strcpy(buffer,"Hello World!\n");
  58. send(new_sock,buffer,13,0);
  59.  
  60. /*---- Read the message from the client into the buffer ----*/
  61. //memset(buffer, 0, sizeof buffer);
  62. if (recv(new_sock, buffer, sizeof(buffer), 0) < 0) {
  63. printf("Can't get message from client\n");
  64. }
  65. else {
  66. printf("Client said %s\n", buffer);
  67. }
  68.  
  69.  
  70. } while(1);
  71.  
  72.  
  73. return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement