#include #include #include #include #include #include #include #include #define PORT 1023 const char MESSAGE[] = "Hi there!\n"; int main( void ) { int SrvSocket, ChildPid; int On = 1; struct linger Linger = { 0 }; char Hostname[80]; struct hostent *pHostEnt = NULL; struct sockaddr_in ServerName = { 0 }; SrvSocket = socket( PF_INET, SOCK_STREAM, IPPROTO_TCP ); if( SrvSocket == -1 ) { perror( "Can't create socket!\n" ); exit( 1 ); } if( setsockopt( SrvSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&On, sizeof( On ) ) ) { perror( "Can't set reuse address on socket!\n" ); exit( 1 ); } Linger.l_onoff = 1; Linger.l_linger = 20; if( setsockopt( SrvSocket, SOL_SOCKET, SO_LINGER, (const char*)&Linger, sizeof( Linger ) ) ) { perror( "Can't set lingering for socket!\n" ); exit( 1 ); } if( gethostname( Hostname, sizeof( Hostname ) ) ) { perror( " Can't get my own hostname!\n" ); exit( 1 ); } pHostEnt = gethostbyname( Hostname ); if( ! pHostEnt ) { perror( "Can't get hostentry!\n" ); exit( 1 ); } memset( &ServerName, 0, sizeof( ServerName ) ); memcpy( &ServerName.sin_addr, pHostEnt->h_addr, pHostEnt->h_length ); ServerName.sin_family = AF_INET; ServerName.sin_port = htons( PORT ); if( bind( SrvSocket, (struct sockaddr*)&ServerName, sizeof( ServerName ) ) ) { perror( "Can't bind socket!\n" ); exit( 1 ); } if( listen(SrvSocket, BACKLOG ) ) { perror( "Can't listen on socket!\n" ); exit( 1 ); } while( 1 ) { struct sockaddr_in ClientName; int SlaveSocket, ClientLength = sizeof( ClientName ); memset( &ClientName, 0, sizeof( ClientName ) ); SlaveSocket = accept( SrvSocket, (struct sockaddr*)&ClientName, &ClientLength ); if( SlaveSocket == -1 ) { perror( "Can't accept connection!\n" ); exit( 1 ); } ChildPid = fork(); sleep( 10 ); switch( ChildPid ) { case -1: perror( "Can't fork!\n" ); exit( 1 ); case 0: close( SrvSocket ); if( getpeername( SlaveSocket, (struct sockaddr*)&ClientName, &ClientLength )) { perror( "Can't get peername!\n" ); } else { printf( "Connection request from %s\n", inet_ntoa( ClientName.sin_addr) ); } write( SlaveSocket, MESSAGE, strlen( MESSAGE ) ); close( SlaveSocket ); exit( 0 ); default: close( SlaveSocket ); } } exit( 0 ); }