45
Écrire un serveur en mode datagram
- /*
- * Simple dgram echo server.
- *
- * socket - AF_INET SOCK_DGRAM
- * bind
- * recvfrom
- * sendto
- *
- * sockaddr_in
- */
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <errno.h>
- #if defined( LINUX )
- #include <string.h>
- #endif
- int open_socket( int portnum ) {
- int sd = -1;
- struct sockaddr_in sd_address;
- socklen_t addrlen = sizeof (struct sockaddr_in);
- if ( (sd = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP )) == -1 )
- goto error;
- sd_address.sin_family = AF_INET;
- sd_address.sin_addr.s_addr = htonl( INADDR_ANY );
- sd_address.sin_port = htons( portnum );
- if ( bind( sd, (struct sockaddr *) &sd_address, addrlen ) != 0 )
- goto error;
- return sd;
- error:
- fprintf( stderr, "%s\n", strerror( errno ) );
- if ( sd != -1 )
- close( sd );
- return -1;
- }
- void echo_input( int socket ) {
- struct sockaddr_in sd_address;
- socklen_t addrlen = sizeof (struct sockaddr_in);
- char buf[4096];
- int n;
- if ( (n = recvfrom( socket, buf, sizeof (buf), 0, (struct sockaddr *) &sd_address, &addrlen )) == -1 )
- goto error;
- if ( (n = sendto( socket, buf, n, 0, (struct sockaddr *) &sd_address, addrlen )) == -1 )
- goto error;
- return;
- error:
- fprintf( stderr, "%s\n", strerror( errno ) );
- }
- int main( int argc, char *argv[] ) {
- int portnum, n;
- int socket, sd;
- switch ( argc ) {
- case 2:
- n = atoi( argv[1] );
- if ( n == 0 )
- goto usage;
- portnum = n;
- break;
- default:
- usage: fprintf( stderr, "%s portnum\n", argv[0] );
- exit( 1 );
- }
- setbuf( stdout, 0 );
- if ( (socket = open_socket( portnum )) == -1 )
- exit( 1 );
- echo_input( socket );
- close( socket );
- exit( 0 );
- }
Commentaires