7
Envoyer des données en mode unix
- /*
- * Sends a string to unix echo server and prints what it returns.
- *
- * socket - AF_UNIX SOCK_STREAM
- * connect
- * write
- * read
- * shutdown
- *
- * struct sockaddr
- */
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <strings.h>
- #include <errno.h>
- #if defined( LINUX )
- #include <string.h>
- #endif
- #include <unistd.h>
- int main( int argc, char **argv ) {
- int sd = -1;
- struct sockaddr sd_address;
- int addrlen = sizeof (struct sockaddr);
- char *sockname;
- char *msg = "HELLO";
- char reply[16];
- switch ( argc ) {
- case 2:
- sockname = argv[1];
- break;
- default:
- usage: fprintf( stderr, "%s sockpath\n", argv[0] );
- exit( 1 );
- }
- 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 ( connect( sd, (struct sockaddr *) &sd_address, addrlen ) == -1 )
- goto error;
- if ( write( sd, msg, strlen( msg ) + 1 ) == -1 )
- goto error;
- if ( read( sd, reply, sizeof(reply) ) == -1 )
- goto error;
- if ( shutdown( sd, 2 ) == -1 )
- goto error;
- close( sd );
- fprintf( stdout, "%s\n", reply );
- exit( 0 );
- error:
- fprintf( stderr, "%s\n", strerror( errno ) );
- if ( sd != -1 )
- close( sd );
- exit( 1 );
- }
Commentaires