1*27700Smckusick .\" Copyright (c) 1986 Regents of the University of California.
2*27700Smckusick .\" All rights reserved.  The Berkeley software License Agreement
3*27700Smckusick .\" specifies the terms and conditions for redistribution.
4*27700Smckusick .\"
5*27700Smckusick .\"	@(#)dgramread.c	6.1 (Berkeley) 05/04/86
6*27700Smckusick .\"
7*27700Smckusick #include <sys/types.h>
8*27700Smckusick #include <sys/socket.h>
9*27700Smckusick #include <netinet/in.h>
10*27700Smckusick #include <stdio.h>
11*27700Smckusick 
12*27700Smckusick /*
13*27700Smckusick  * In the included file <netinet/in.h> a sockaddr_in is defined as follows:
14*27700Smckusick  * struct sockaddr_in {
15*27700Smckusick  *	short	sin_family;
16*27700Smckusick  *	u_short	sin_port;
17*27700Smckusick  *	struct in_addr sin_addr;
18*27700Smckusick  *	char	sin_zero[8];
19*27700Smckusick  * };
20*27700Smckusick  */
21*27700Smckusick 
22*27700Smckusick /*
23*27700Smckusick  * This program creates a datagram socket, binds a name to it, then reads
24*27700Smckusick  * from the socket.
25*27700Smckusick  */
26*27700Smckusick 
27*27700Smckusick main()
28*27700Smckusick {
29*27700Smckusick 	int             sock, length;
30*27700Smckusick 	struct sockaddr_in name;
31*27700Smckusick 	char            buf[1024];
32*27700Smckusick 
33*27700Smckusick 	/* Create socket from which to read. */
34*27700Smckusick 	sock = socket(AF_INET, SOCK_DGRAM, 0);
35*27700Smckusick 	if (sock < 0) {
36*27700Smckusick 		perror("opening datagram socket");
37*27700Smckusick 		exit(-1);
38*27700Smckusick 	}
39*27700Smckusick 	/* Create name with wildcards. */
40*27700Smckusick 	name.sin_family = AF_INET;
41*27700Smckusick 	name.sin_addr.s_addr = INADDR_ANY;
42*27700Smckusick 	name.sin_port = 0;
43*27700Smckusick 	if (bind(sock, &name, sizeof(name))) {
44*27700Smckusick 		close(sock);
45*27700Smckusick 		perror("binding datagram socket");
46*27700Smckusick 	}
47*27700Smckusick 	/* Find assigned port value and print it out. */
48*27700Smckusick 	length = sizeof(name);
49*27700Smckusick 	if (getsockname(sock, &name, &length)) {
50*27700Smckusick 		close(sock);
51*27700Smckusick 		perror("getting socket name");
52*27700Smckusick 	}
53*27700Smckusick 	printf("Socket has port #%d\en", ntohs(name.sin_port));
54*27700Smckusick 	/* Read from the socket */
55*27700Smckusick 	if (read(sock, buf, 1024, 0) < 0)
56*27700Smckusick 		perror("receiving datagram packet");
57*27700Smckusick 	printf("-->%s\en", buf);
58*27700Smckusick 	close(sock);
59*27700Smckusick }
60