/* pingserver.c - a server program that uses the socket interface to tcp */ /* this program sends back to clients all data it receives */ #include #include #include #include #include #include #include #include #include "server.h" #include "tcpblockio.h" #define BUFSIZE 10000000 #define listening_depth 2 char buffer[BUFSIZE]; void server( int server_port, char *server_name, int argc, char *argv[] ) { int n, len, fd, client_fd, amount, nettemp; struct sockaddr_in address, client; fd = openserver(server_port, server_name, &address); /* we are now successfully established as a server */ for( ; ; ) { /* now accept a client connection (we'll block until one arrives) */ len = sizeof(client); if( (client_fd = accept(fd, (struct sockaddr *)&client, &len)) < 0 ) { perror("server accept"); exit(EXIT_FAILURE); } /* we are now successfully connected to a remote client */ fprintf(stderr, "server: connected to client at internet address %s, port %d\n", inet_ntoa(client.sin_addr), ntohs(client.sin_port)); /* first read the size of the message blocks */ readblock(client_fd, (char *)&nettemp, sizeof(nettemp)); amount = ntohl(nettemp); /* now read data messages from client then write them back */ while( (n = readblock(client_fd, buffer, amount)) > 0 ) { writeblock(client_fd, buffer, n); } /* close the connection to the client */ fprintf(stderr, "server: disconnected from client at internet address %s, port %d\n", inet_ntoa(client.sin_addr), ntohs(client.sin_port)); if( close(client_fd) < 0 ) { perror("server close connection to client"); exit(EXIT_FAILURE); } } /* close the "listening post" socket by which server made connections */ if( close(fd) < 0 ) { perror("server close"); exit(EXIT_FAILURE); } }