Advertisement
Guest User

Untitled

a guest
Dec 17th, 2017
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. #include <iostream>;
  2. #include <iomanip>;
  3. using namespace std;
  4. #include <stdlib.h>;
  5. #include <stdio.h>;
  6. #include <errno.h>;
  7. #include <string.h>;
  8. #include <netdb.h>;
  9. #include <sys/types.h>
  10. #include <unistd.h>
  11.  
  12.  
  13. #define EOK 0
  14. const int MAXLINE = 40;
  15.  
  16. // диагностика ошибки ...
  17. void errx( const char *msg, int err ) {
  18. perror( msg );
  19. if( err != EOK ) errno = err;
  20. exit( EXIT_FAILURE );
  21. };
  22.  
  23. // ретранслятор тестовых пакетов TCP
  24. static char data[ MAXLINE ];
  25. void retrans( int sc ) {
  26. int rc = read( sc, data, MAXLINE );
  27. if( rc > 0 ) {
  28. rc = write( sc, data, strlen( data ) + 1 );
  29. if ( rc < 0 ) perror( "write data failed" );
  30. }
  31. else if( rc < 0 ) { perror( "read data failed" ); return; }
  32. else if( rc == 0 ) { cout << "client closed connection" << endl; return; };
  33. return;
  34. };
  35.  
  36. // создание и подготовка прослушивающего сокета
  37. static struct sockaddr_in addr;
  38. int getsocket( in_port_t p ) {
  39. int rc = 1, ls;
  40. if( -1 == ( ls = socket( AF_INET, SOCK_STREAM, 0 ) ) )
  41. errx( "create stream socket failed", ls );
  42. if( setsockopt( ls, SOL_SOCKET, SO_REUSEADDR, &rc, sizeof( rc ) ) != 0 )
  43. errx( "set socket option failed", ls );
  44. memset( &addr, 0, sizeof( addr ) );
  45. addr.sin_family = AF_INET;
  46. addr.sin_port = htons( p );
  47. addr.sin_addr.s_addr = htonl( INADDR_ANY );
  48. if( bind( ls, (struct sockaddr*)&addr, sizeof( sockaddr ) ) != 0 )
  49. errx( "bind socket address failed", ls );
  50. if( listen( ls, 25 ) != 0 ) errx( "put socket in listen state failed", ls );
  51. std::cout << "waiting on port " << p << " ..." << std::endl;
  52. return ls;
  53. };
  54.  
  55. // уровень отладочного вывода сервера
  56. int debug = 0;
  57. void setv( int argc, char *argv[] ) {
  58. debug = ( argc > 1 && 0 == strcmp( argv[ 1 ], "-v" ) ) ? 1 : 0;
  59. if( debug ) std::cout << "verbose mode" << std::endl;
  60. }
  61.  
  62. // ретранслятор c fork
  63. int main( int argc, char *argv[] ) {
  64. int ls = getsocket( 51001 ), rs;
  65. setv( argc, argv );
  66. while( true ) {
  67. if( ( rs = accept( ls, NULL, NULL ) ) < 0 ) errx( "accept error", ls );
  68. pid_t pid = fork();
  69. if( pid < 0 ) errx( "fork error", ls );
  70. if( pid == 0 ) {
  71. close( ls );
  72. retrans( rs );
  73. close( rs );
  74. if( debug ) cout << "*" << flush;
  75. exit( EXIT_SUCCESS );
  76. }
  77. else close( rs );
  78. };
  79. exit( EXIT_SUCCESS );
  80. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement