Imported Debian version 1.1.6
[debian/ipip] / test / udp_o.c
1 /* udp_o.c -- read packets from the network */
2
3 #include <sys/types.h>
4 #include <sys/socket.h>
5 #include <netinet/in.h>
6 #include <netdb.h>
7
8 #include <stdio.h>
9 #include <string.h>
10 #include <ctype.h>
11
12 #define BUFSIZE 1024
13 #define UDP_PORT 10094
14
15 main(argc, argv)
16         int argc;
17         char *argv[];
18 {
19         int sock, fromlen, l, i, portno;
20         char buf[BUFSIZE], *p;
21         struct sockaddr_in from;
22
23         portno = UDP_PORT;
24
25         /* Test arguments */
26         if(argc>2){
27                 fprintf(stderr,"Usage: %s [<portnumber>]\n",argv[0]);
28                 exit(1);
29         }
30         if(argc>1)portno = atoi(argv[1]);
31
32         /* Create socket */
33         sock = socket(AF_INET, SOCK_DGRAM, 0);
34         if (sock<0) {
35                 perror("opening raw socket");
36                 exit(1);
37         }
38
39         bzero((char *)&from, sizeof from);
40         from.sin_family = AF_INET;
41         from.sin_addr.s_addr = htonl(INADDR_ANY);
42         from.sin_port = htons(portno);
43         if (bind(sock, (struct sockaddr *)&from, sizeof from) < 0){
44                 perror("binding UDP socket");
45                 exit(1);
46         }
47
48         l = 0;
49         while(l>-1){
50                 fromlen = sizeof from;
51                 l = recvfrom(sock, buf, BUFSIZE, 0, 
52                         (struct sockaddr *)&from, &fromlen);
53                 if(l<0){
54                         perror("udp socket");
55                         close(sock);
56                         exit(2);
57                 }
58                 fprintf(stdout,"---------->recv %d bytes from port %d host %s\n", l,
59                                 ntohs(from.sin_port),
60                                 (char *)inet_ntoa(from.sin_addr));
61
62                 fprintf(stdout,"{%d.%d.%d.%d->%d.%d.%d.%d}\n",buf[12],buf[13],
63                         buf[14],buf[15],buf[16],buf[17],buf[18],buf[19]);
64
65                 for(p=buf+40,i=0;i<(l-40);i++,p++){
66                         if(isprint(*p))putc(*p,stdout);
67                         else putc('.',stdout);
68                 }
69                                 putc('\n',stdout);
70                 fflush(stdout);
71         }
72
73         /* all done, close the socket and exit */
74         close(sock);
75         exit(0);
76 }