6

Écrire un serveur en mode datagram

  1. /*
  2.  * Simple dgram echo server.
  3.  *
  4.  *   socket - AF_INET SOCK_DGRAM
  5.  *   bind
  6.  *   recvfrom
  7.  *   sendto
  8.  *
  9.  *   sockaddr_in
  10.  */
  11.  
  12. #include <sys/types.h>
  13. #include <sys/socket.h>
  14. #include <netinet/in.h>
  15.  
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <errno.h>
  19. #if defined( LINUX )
  20. #include <string.h>
  21. #endif
  22.  
  23. int open_socket( int portnum ) {
  24.     int sd = -1;
  25.     struct sockaddr_in sd_address;
  26.     socklen_t addrlen = sizeof (struct sockaddr_in);
  27.  
  28.     if ( (sd = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP )) == -1 )
  29.         goto error;
  30.  
  31.     sd_address.sin_family = AF_INET;
  32.     sd_address.sin_addr.s_addr = htonl( INADDR_ANY );
  33.     sd_address.sin_port = htons( portnum );
  34.  
  35.     if ( bind( sd, (struct sockaddr *) &sd_address, addrlen ) != 0 )
  36.         goto error;
  37.  
  38.     return sd;
  39.  
  40. error:
  41.  
  42.     fprintf( stderr, "%s\n", strerror( errno ) );
  43.     if ( sd != -1 )
  44.         close( sd );
  45.     return -1;
  46. }
  47.  
  48. void echo_input( int socket ) {
  49.     struct sockaddr_in sd_address;
  50.     socklen_t addrlen = sizeof (struct sockaddr_in);
  51.  
  52.     char buf[4096];
  53.     int n;
  54.  
  55.     if ( (n = recvfrom( socket, buf, sizeof (buf), 0, (struct sockaddr *) &sd_address, &addrlen )) == -1 )
  56.         goto error;
  57.     if ( (n = sendto( socket, buf, n, 0, (struct sockaddr *) &sd_address, addrlen )) == -1 )
  58.         goto error;
  59.  
  60.     return;
  61.  
  62. error:
  63.    
  64.     fprintf( stderr, "%s\n", strerror( errno ) );
  65. }
  66.  
  67. int main( int argc, char *argv[] ) {
  68.     int portnum, n;
  69.     int socket, sd;
  70.  
  71.     switch ( argc ) {
  72.     case 2:
  73.         n = atoi( argv[1] );
  74.         if ( n == 0 )
  75.             goto usage;
  76.         portnum = n;
  77.         break;
  78.     default:
  79.         usage: fprintf( stderr, "%s portnum\n", argv[0] );
  80.         exit( 1 );
  81.     }
  82.     setbuf( stdout, 0 );
  83.  
  84.     if ( (socket = open_socket( portnum )) == -1 )
  85.         exit( 1 );
  86.  
  87.     echo_input( socket );
  88.  
  89.     close( socket );
  90.  
  91.     exit( 0 );
  92. }

Commentaires

Pour ajouter un commentaire, cliquez ici.