"Fossies" - the Fresh Open Source Software Archive

Member "portfwd-0.29/tools/udp_rcv.cc" (18 Sep 2002, 1786 Bytes) of package /linux/privat/old/portfwd-0.29.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file.

    1 /*
    2   udp_rcv.c
    3 
    4   gcc -Wall -o udp_rcv udp_rcv.c
    5 
    6   udp_rcv <port>
    7 
    8   $Id: udp_rcv.cc,v 1.2 2002/09/18 18:42:07 evertonm Exp $
    9  */
   10 
   11 #include <stdlib.h>
   12 #include <stdio.h>
   13 #include <sys/types.h>
   14 #include <sys/socket.h>
   15 #include <string.h>
   16 #include <errno.h>
   17 #include <netinet/in.h>
   18 #include <arpa/inet.h>
   19 #include <unistd.h>
   20 
   21 const int BUF_SZ = 8192;
   22 
   23 int main(int argc, char *argv[])
   24 {
   25   int          port;
   26   int          sd;
   27   struct       sockaddr_in sa;
   28   char         buf[BUF_SZ];
   29   int          rd;
   30   unsigned int sa_len;
   31   socklen_t cli_sa_len;
   32   struct sockaddr_in cli_sa;
   33 
   34   cli_sa_len = sizeof(cli_sa);
   35 
   36   if (argc != 2) {
   37     printf("usage: %s <port>\n", argv[0]);
   38     exit(1);
   39   }
   40 
   41   port = atoi(argv[1]);
   42 
   43   sd = socket(AF_INET, SOCK_DGRAM, 17);
   44   if (sd == -1) {
   45     fprintf(stderr, "Can't create UDP socket: %s\n", strerror(errno));
   46     exit(1);
   47   }
   48     
   49   sa.sin_family      = AF_INET;
   50   sa.sin_port        = htons(port);
   51   sa.sin_addr.s_addr = htonl(INADDR_ANY);
   52   memset((char *) sa.sin_zero, 0, sizeof(sa.sin_zero));
   53   sa_len = sizeof(sa);
   54 
   55   if (bind(sd, (struct sockaddr *) &sa, sa_len)) {
   56     fprintf(stderr, "Can't bind UDP socket: %s: %s:%d\n", strerror(errno), inet_ntoa(sa.sin_addr), port);
   57     close(sd);
   58     exit(1);
   59   }
   60 
   61   for (;;) { /* forever */
   62     fprintf(stderr, "Waiting UDP packet on %s:%d\n", inet_ntoa(sa.sin_addr), port);
   63 
   64     rd = recvfrom(sd, buf, BUF_SZ, 0, (struct sockaddr *) &cli_sa, &cli_sa_len);
   65     if (!rd)
   66       break;
   67     if (rd == -1) {
   68       fprintf(stderr, "Can't receive UDP packet: %s\n", strerror(errno));
   69       break;
   70     }
   71 
   72     printf("%s:%d (%d) \"%s\"\n", inet_ntoa(cli_sa.sin_addr), ntohs(cli_sa.sin_port), rd, buf);
   73   }
   74 
   75   if (close(sd))
   76     fprintf(stderr, "close on socket failed: %s\n", strerror(errno));
   77 
   78   return 0;
   79 }
   80