"Fossies" - the Fresh Open Source Software Archive

Member "portfwd-0.29/tools/udp_snd.cc" (15 May 2001, 1809 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_snd.c
    3 
    4   gcc -Wall -o udp_snd udp_snd.c
    5 
    6   udp_snd <host> <port>
    7 
    8   $Id: udp_snd.cc,v 1.1.1.1 2001/05/15 00:25:13 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 #include <netdb.h>
   21 
   22 const int BUF_SZ = 8192;
   23 
   24 int main(int argc, char *argv[])
   25 {
   26   int            port;
   27   int            sd;
   28   struct         sockaddr_in sa;
   29   char           buf[BUF_SZ];
   30   int            rd, wr;
   31   const char     *host;
   32   struct hostent *he;
   33   unsigned int   sa_len = sizeof(sa);
   34 
   35   if (argc != 3) {
   36     printf("usage: %s <host> <port>\n", argv[0]);
   37     exit(1);
   38   }
   39 
   40   host = argv[1];
   41   port = atoi(argv[2]);
   42 
   43   he = gethostbyname(host);
   44   if (!he) {
   45     fprintf(stderr, "Can't solve hostname: %s\n", host);
   46     exit(1);
   47   }
   48 
   49   sd = socket(AF_INET, SOCK_DGRAM, 17);
   50   if (sd == -1) {
   51     fprintf(stderr, "Can't create UDP socket: %s\n", strerror(errno));
   52     exit(1);
   53   }
   54     
   55   sa.sin_family      = AF_INET;
   56   sa.sin_port        = htons(port);
   57   sa.sin_addr.s_addr = *((unsigned int *) *he->h_addr_list);
   58   memset((char *) sa.sin_zero, 0, sizeof(sa.sin_zero));
   59 
   60   for (;;) { /* forever */
   61     rd = read(0, buf, BUF_SZ);
   62     if (!rd)
   63       break;
   64     if (rd == -1)
   65       fprintf(stderr, "Can't read from stdin\n");
   66 
   67     wr = sendto(sd, buf, rd, 0, (struct sockaddr *) &sa, sa_len);
   68     if (rd == -1) {
   69       fprintf(stderr, "Can't send UDP packet: %s\n", strerror(errno));
   70       break;
   71     }
   72     if (wr < rd) 
   73       fprintf(stderr, "udp_snd: Partial send\n");
   74 
   75     printf("%s:%d (%d) \"%s\"\n", inet_ntoa(sa.sin_addr), ntohs(sa.sin_port), wr, buf);
   76   }
   77 
   78   if (close(sd))
   79     fprintf(stderr, "close on socket failed: %s\n", strerror(errno));
   80 
   81   return 0;
   82 }