#include #include #include #include #include #include #include #include #include #define MYPORT 3490 #define BACKLOG 10 #define DATASIZE (32 * 1024 + 1) int main( void ) { int sockfd, new_fd; struct sockaddr_in my_addr; struct sockaddr_in their_addr; int sin_size, i, total, n; char buf[ DATASIZE + 1 ]; if ( ( sockfd = socket( AF_INET, SOCK_STREAM, 0 ) ) == -1 ) { perror( "socket" ); exit( 1 ); } my_addr.sin_family = AF_INET; my_addr.sin_port = htons( MYPORT ); my_addr.sin_addr.s_addr = INADDR_ANY; memset( &( my_addr.sin_zero ), '\0', 8 ); if ( bind( sockfd, ( struct sockaddr * )&my_addr, sizeof( struct sockaddr ) ) == -1 ) { perror( "bind" ); exit( 1 ); } if ( listen( sockfd, BACKLOG ) == -1 ) { perror( "listen" ); exit( 1 ); } while ( 1 ) { sin_size = sizeof( struct sockaddr_in ); if ( ( new_fd = accept( sockfd, (struct sockaddr *)&their_addr, &sin_size ) ) == -1 ) { perror( "accept" ); continue; } printf( "server: got connection from %s\n", inet_ntoa( their_addr.sin_addr ) ); total = DATASIZE; i = 0; n = 0; while ( total > 0 ) { if ( ( i = recv( new_fd, buf, total, 0 ) ) == -1 ) { perror( "recv" ); exit( 1 ); } else if ( i == 0 ) { printf( "peer closed connection\n" ); break; } else { printf( "\t | received %d bytes from %d " \ "requested (%0.2f%%).\n", i, total, 100.0f * i / total ); total -= i; n ++; } } printf( "\t `-> got %d bytes with %d recv()s\n", DATASIZE, n ); printf( "server: closed connection to %s\n", inet_ntoa( their_addr.sin_addr ) ); close( new_fd ); } return 0; } /* author: Gustavo Sverzut Barbieri (http://www.gustavobarbieri.com.br) */