4
Write a server in unix mode
- /*
- * Simple unix echo server.
- *
- * socket - AF_UNIX SOCK_STREAM
- * bind
- * listen
- * accept
- * read
- * write
- * unlink
- *
- * sockaddr
- */
- #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( char *sockname ) {
- int sd = -1;
- struct sockaddr sd_address;
- socklen_t addrlen = sizeof (struct sockaddr);
- if ( (sd = socket( PF_UNIX, SOCK_STREAM, 0 )) == -1 )
- goto error;
- sd_address.sa_family = AF_UNIX;
- (void) strcpy( sd_address.sa_data, sockname );
- if ( bind( sd, &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 sd_address;
- socklen_t addrlen = sizeof (struct sockaddr);
- char buf[4096];
- int n;
- sd = accept( socket, &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[] ) {
- char *sockname;
- int socket, sd;
- switch ( argc ) {
- case 2:
- sockname = argv[1];
- break;
- default:
- usage: fprintf( stderr, "%s sockpath\n", argv[0] );
- exit( 1 );
- }
- if ( (socket = open_socket( sockname )) == -1 )
- exit( 1 );
- echo_input( socket );
- close( socket );
- unlink( sockname ); /* free local address */
- exit( 0 );
- }
Comments