3

Envoyer des données en TCP

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

Commentaires

Pour ajouter un commentaire, cliquez ici.