5

Send data in unix mode

  1. /*
  2.  * Sends a string to unix echo server and prints what it returns.
  3.  *
  4.  *   socket - AF_UNIX SOCK_STREAM
  5.  *   connect
  6.  *   write
  7.  *   read
  8.  *   shutdown
  9.  *
  10.  *   struct sockaddr
  11.  */
  12.  
  13. #include <sys/types.h>
  14. #include <sys/socket.h>
  15. #include <netinet/in.h>
  16.  
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <strings.h>
  20. #include <errno.h>
  21. #if defined( LINUX )
  22. #include <string.h>
  23. #endif
  24.  
  25. #include <unistd.h>
  26.  
  27. int main( int argc, char **argv ) {
  28.     int sd = -1;
  29.     struct sockaddr sd_address;
  30.     int addrlen = sizeof (struct sockaddr);
  31.  
  32.     char *sockname;
  33.  
  34.     char *msg = "HELLO";
  35.     char reply[16];
  36.  
  37.     switch ( argc ) {
  38.     case 2:
  39.         sockname = argv[1];
  40.         break;
  41.     default:
  42.         usage: fprintf( stderr, "%s sockpath\n", argv[0] );
  43.         exit( 1 );
  44.     }
  45.  
  46.     if ( (sd = socket( PF_UNIX, SOCK_STREAM, 0 )) == -1 )
  47.         goto error;
  48.  
  49.     sd_address.sa_family = AF_UNIX;
  50.     (void) strcpy( sd_address.sa_data, sockname );
  51.  
  52.     if ( connect( sd, (struct sockaddr *) &sd_address, addrlen ) == -1 )
  53.         goto error;
  54.  
  55.     if ( write( sd, msg, strlen( msg ) + 1 ) == -1 )
  56.         goto error;
  57.  
  58.     if ( read( sd, reply, sizeof(reply) ) == -1 )
  59.         goto error;
  60.  
  61.     if ( shutdown( sd, 2 ) == -1 )
  62.         goto error;
  63.  
  64.     close( sd );
  65.  
  66.     fprintf( stdout, "%s\n", reply );
  67.  
  68.     exit( 0 );
  69.  
  70. error:
  71.  
  72.     fprintf( stderr, "%s\n", strerror( errno ) );
  73.     if ( sd != -1 )
  74.         close( sd );
  75.     exit( 1 );
  76. }

Comments

Your comment:
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip help 2000

Enter a maximum of 2000 characters.
Improve the presentation of your text with the following formatting tags:
[p]paragraph[/p], [b]bold[/b], [i]italics[/i], [u]underline[/u], [s]strike[/s], [quote]citation[/quote], [pre]as is[/pre], [br]line break,
[url]http://www.izend.org[/url], [url=http://www.izend.org]site[/url], [email]izend@izend.org[/email], [email=izend@izend.org]izend[/email],
[code]command[/code], [code=language]source code in c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].