7
Write a server in stream mode
- /*
- * Simple stream echo server.
- *
- * socket - AF_INET SOCK_STREAM
- * bind
- * listen
- * accept
- * read
- * write
- *
- * sockaddr_in
- */
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <errno.h>
- #if defined( LINUX )
- #include <string.h>
- #endif
- int open_socket( int portnum ) {
- int sd = -1;
- struct sockaddr_in sd_address;
- socklen_t addrlen = sizeof (struct sockaddr_in);
- int sockoptval, sockoptlen;
- if ( (sd = socket( PF_INET, SOCK_STREAM, IPPROTO_TCP )) == -1 )
- goto error;
- sockoptval = 1; /* on */
- sockoptlen = sizeof(sockoptval);
- if ( setsockopt( sd, SOL_SOCKET, SO_REUSEADDR, &sockoptval, sockoptlen ) < 0 )
- goto error;
- sd_address.sin_family = AF_INET;
- sd_address.sin_addr.s_addr = htonl( INADDR_ANY );
- sd_address.sin_port = htons( portnum );
- if ( bind( sd, (struct sockaddr *) &sd_address, addrlen ) != 0 )
- goto error;
- if ( listen( sd, 5 ) != 0 )
- goto error;
- return sd;
- error:
- fprintf( stderr, "%s\n", strerror( errno ) );
- if ( sd != -1 )
- close( sd );
- return -1;
- }
- void echo_input( int socket ) {
- int sd = -1;
- struct sockaddr_in sd_address;
- socklen_t addrlen = sizeof(struct sockaddr_in);
- char buf[4096];
- int n;
- sd = accept( socket, (struct sockaddr *) &sd_address, &addrlen );
- if ( sd == -1 )
- goto error;
- while ( (n = read( sd, buf, sizeof(buf) )) != 0 )
- if ( write( sd, buf, n ) == -1 )
- break;
- close( sd );
- return;
- error:
- fprintf( stderr, "%s\n", strerror( errno ) );
- if ( sd != -1 )
- close( sd );
- }
- int main( int argc, char *argv[] ) {
- int portnum, n;
- int socket, sd;
- switch ( argc ) {
- case 2:
- n = atoi( argv[1] );
- if ( n == 0 )
- goto usage;
- portnum = n;
- break;
- default:
- usage: fprintf( stderr, "%s portnum\n", argv[0] );
- exit( 1 );
- }
- if ( (socket = open_socket( portnum )) == -1 )
- exit( 1 );
- echo_input( socket );
- close( socket );
- exit( 0 );
- }
Comments