Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>;
- #include <iomanip>;
- using namespace std;
- #include <stdlib.h>;
- #include <stdio.h>;
- #include <errno.h>;
- #include <string.h>;
- #include <netdb.h>;
- #include <sys/types.h>
- #include <unistd.h>
- #define EOK 0
- const int MAXLINE = 40;
- // диагностика ошибки ...
- void errx( const char *msg, int err ) {
- perror( msg );
- if( err != EOK ) errno = err;
- exit( EXIT_FAILURE );
- };
- // ретранслятор тестовых пакетов TCP
- static char data[ MAXLINE ];
- void retrans( int sc ) {
- int rc = read( sc, data, MAXLINE );
- if( rc > 0 ) {
- rc = write( sc, data, strlen( data ) + 1 );
- if ( rc < 0 ) perror( "write data failed" );
- }
- else if( rc < 0 ) { perror( "read data failed" ); return; }
- else if( rc == 0 ) { cout << "client closed connection" << endl; return; };
- return;
- };
- // создание и подготовка прослушивающего сокета
- static struct sockaddr_in addr;
- int getsocket( in_port_t p ) {
- int rc = 1, ls;
- if( -1 == ( ls = socket( AF_INET, SOCK_STREAM, 0 ) ) )
- errx( "create stream socket failed", ls );
- if( setsockopt( ls, SOL_SOCKET, SO_REUSEADDR, &rc, sizeof( rc ) ) != 0 )
- errx( "set socket option failed", ls );
- memset( &addr, 0, sizeof( addr ) );
- addr.sin_family = AF_INET;
- addr.sin_port = htons( p );
- addr.sin_addr.s_addr = htonl( INADDR_ANY );
- bind( ls, (struct sockaddr*)&addr, sizeof( sockaddr ) );
- // errx( "bind socket address failed", ls );
- if( listen( ls, 25 ) != 0 ) errx( "put socket in listen state failed", ls );
- std::cout << "waiting on port " << p << " ..." << std::endl;
- return ls;
- };
- // уровень отладочного вывода сервера
- int debug = 0;
- void setv( int argc, char *argv[] ) {
- debug = ( argc > 1 && 0 == strcmp( argv[ 1 ], "-v" ) ) ? 1 : 0;
- if( debug ) std::cout << "verbose mode" << std::endl;
- }
- // ретранслятор c fork
- int main( int argc, char *argv[] ) {
- int ls = getsocket( 51001 ), rs;
- setv( argc, argv );
- while( true ) {
- if( ( rs = accept( ls, NULL, NULL ) ) < 0 ) errx( "accept error", ls );
- pid_t pid = fork();
- if( pid < 0 ) errx( "fork error", ls );
- if( pid == 0 ) {
- close( ls );
- retrans( rs );
- close( rs );
- if( debug ) cout << "*" << flush;
- exit( EXIT_SUCCESS );
- }
- else close( rs );
- };
- exit( EXIT_SUCCESS );
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement