Advertisement
akurczyk

serwer

Mar 6th, 2014
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.66 KB | None | 0 0
  1. /*
  2. ** server.c -- serwer używający gniazd strumieniowych
  3. */
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <unistd.h>
  8. #include <errno.h>
  9. #include <string.h>
  10. #include <sys/types.h>
  11. #include <sys/socket.h>
  12. #include <netinet/in.h>
  13. #include <arpa/inet.h>
  14. #include <sys/wait.h>
  15. #include <signal.h>
  16.  
  17. #define MYPORT 3490 // port, z którym będą się łączyli użytkownicy
  18.  
  19. #define BACKLOG 10 // jak dużo możę być oczekujących połączeń w kolejce
  20.  
  21. void sigchld_handler( int s )
  22. {
  23. while( wait( NULL ) > 0 );
  24.  
  25. }
  26.  
  27. int main( void )
  28. {
  29. int sockfd, new_fd; // nasłuchuj na sock_fd, nowe połaczenia na new_fd
  30. struct sockaddr_in my_addr; // informacja o moim adresie
  31. struct sockaddr_in their_addr; // informacja o adresie osoby łączącej się
  32. int sin_size;
  33. struct sigaction sa;
  34. int yes = 1;
  35.  
  36. if(( sockfd = socket( AF_INET, SOCK_STREAM, 0 ) ) == - 1 ) {
  37. perror( "socket" );
  38. exit( 1 );
  39. }
  40.  
  41. if( setsockopt( sockfd, SOL_SOCKET, SO_REUSEADDR, & yes, sizeof( int ) ) == - 1 ) {
  42. perror( "setsockopt" );
  43. exit( 1 );
  44. }
  45.  
  46. my_addr.sin_family = AF_INET; // host byte order
  47. my_addr.sin_port = htons( MYPORT ); // short, network byte order
  48. my_addr.sin_addr.s_addr = INADDR_ANY; // uzupełnij moim adresem IP
  49. memset( &( my_addr.sin_zero ), '\0', 8 ); // wyzeruj resztę struktury
  50.  
  51. if( bind( sockfd,( struct sockaddr * ) & my_addr, sizeof( struct sockaddr ) )
  52. == - 1 ) {
  53. perror( "bind" );
  54. exit( 1 );
  55. }
  56.  
  57. if( listen( sockfd, BACKLOG ) == - 1 ) {
  58. perror( "listen" );
  59. exit( 1 );
  60. }
  61.  
  62. sa.sa_handler = sigchld_handler; // zbierz martwe procesy
  63. sigemptyset( & sa.sa_mask );
  64. sa.sa_flags = SA_RESTART;
  65. if( sigaction( SIGCHLD, & sa, NULL ) == - 1 ) {
  66. perror( "sigaction" );
  67. exit( 1 );
  68. }
  69.  
  70. while( 1 ) { // głowna pętla accept()
  71. sin_size = sizeof( struct sockaddr_in );
  72. if(( new_fd = accept( sockfd,( struct sockaddr * ) & their_addr,
  73. & sin_size ) ) == - 1 ) {
  74. perror( "accept" );
  75. continue;
  76. }
  77. printf( "server: got connection from %s\n",
  78. inet_ntoa( their_addr.sin_addr ) );
  79. if( !fork() ) { // to jest proces-dziecko
  80. close( sockfd ); // dziecko nie potrzebuje gniazda nasłuchującego
  81. if( send( new_fd, "Hello, world!\n", 14, 0 ) == - 1 )
  82. perror( "send" );
  83.  
  84. close( new_fd );
  85. exit( 0 );
  86. }
  87. close( new_fd ); // rodzic nie potrzebuje tego
  88. }
  89.  
  90. return 0;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement