5

Envoyer des données en UDP

  1. /*
  2.  * Sends a string to udp echo server and prints what it returns.
  3.  *
  4.  *   socket - PF_INET SOCK_DGRAM IPPROTO_UDP
  5.  *   htonl
  6.  *   sendto
  7.  *   recvfrom
  8.  *   strerror
  9.  *
  10.  *   struct sockaddr_in
  11.  */
  12.  
  13. #include <sys/types.h>
  14. #include <sys/socket.h>
  15. #include <sys/fcntl.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_DGRAM, IPPROTO_UDP )) == -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 ( sendto( sd, msg, strlen( msg ) + 1, 0, (struct sockaddr *) &sd_address, addrlen ) == -1 )
  48.         goto error;
  49.  
  50.     if ( recvfrom( sd, reply, sizeof (reply), 0, 0, &addrlen ) == -1 )
  51.         goto error;
  52.  
  53.     close( sd );
  54.  
  55.     fprintf( stdout, "%s\n", reply );
  56.  
  57.     exit( 0 );
  58.  
  59. error:
  60.  
  61.     fprintf( stderr, "%s\n", strerror( errno ) );
  62.     if ( sd != -1 )
  63.         close( sd );
  64.     exit( 1 );
  65. }

Commentaires

Pour ajouter un commentaire, cliquez ici.