File: udp_o.c

package info (click to toggle)
ipip 1.0-1
  • links: PTS
  • area: main
  • in suites: hamm
  • size: 204 kB
  • ctags: 139
  • sloc: ansic: 1,397; sh: 116; makefile: 57
file content (76 lines) | stat: -rw-r--r-- 1,572 bytes parent folder | download | duplicates (10)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/* udp_o.c -- read packets from the network */

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define BUFSIZE 1024
#define UDP_PORT 10094

main(argc, argv)
	int argc;
	char *argv[];
{
	int sock, fromlen, l, i, portno;
	char buf[BUFSIZE], *p;
	struct sockaddr_in from;

	portno = UDP_PORT;

	/* Test arguments */
	if(argc>2){
		fprintf(stderr,"Usage: %s [<portnumber>]\n",argv[0]);
		exit(1);
	}
	if(argc>1)portno = atoi(argv[1]);

	/* Create socket */
	sock = socket(AF_INET, SOCK_DGRAM, 0);
	if (sock<0) {
		perror("opening raw socket");
		exit(1);
	}

	bzero((char *)&from, sizeof from);
	from.sin_family = AF_INET;
	from.sin_addr.s_addr = htonl(INADDR_ANY);
	from.sin_port = htons(portno);
	if (bind(sock, (struct sockaddr *)&from, sizeof from) < 0){
		perror("binding UDP socket");
		exit(1);
	}

	l = 0;
	while(l>-1){
		fromlen = sizeof from;
		l = recvfrom(sock, buf, BUFSIZE, 0, 
			(struct sockaddr *)&from, &fromlen);
		if(l<0){
			perror("udp socket");
			close(sock);
			exit(2);
		}
		fprintf(stdout,"---------->recv %d bytes from port %d host %s\n", l,
				ntohs(from.sin_port),
				(char *)inet_ntoa(from.sin_addr));

		fprintf(stdout,"{%d.%d.%d.%d->%d.%d.%d.%d}\n",buf[12],buf[13],
			buf[14],buf[15],buf[16],buf[17],buf[18],buf[19]);

		for(p=buf+40,i=0;i<(l-40);i++,p++){
			if(isprint(*p))putc(*p,stdout);
			else putc('.',stdout);
		}
				putc('\n',stdout);
		fflush(stdout);
	}

	/* all done, close the socket and exit */
	close(sock);
	exit(0);
}