127700Smckusick .\" Copyright (c) 1986 Regents of the University of California.
227700Smckusick .\" All rights reserved.  The Berkeley software License Agreement
327700Smckusick .\" specifies the terms and conditions for redistribution.
427700Smckusick .\"
5*27740Smckusick .\"	@(#)dgramread.c	6.2 (Berkeley) 05/06/86
627700Smckusick .\"
727700Smckusick #include <sys/types.h>
827700Smckusick #include <sys/socket.h>
927700Smckusick #include <netinet/in.h>
1027700Smckusick #include <stdio.h>
1127700Smckusick 
1227700Smckusick /*
1327700Smckusick  * In the included file <netinet/in.h> a sockaddr_in is defined as follows:
1427700Smckusick  * struct sockaddr_in {
1527700Smckusick  *	short	sin_family;
1627700Smckusick  *	u_short	sin_port;
1727700Smckusick  *	struct in_addr sin_addr;
1827700Smckusick  *	char	sin_zero[8];
1927700Smckusick  * };
20*27740Smckusick  *
2127700Smckusick  * This program creates a datagram socket, binds a name to it, then reads
2227700Smckusick  * from the socket.
2327700Smckusick  */
2427700Smckusick main()
2527700Smckusick {
2627700Smckusick 	int             sock, length;
2727700Smckusick 	struct sockaddr_in name;
2827700Smckusick 	char            buf[1024];
2927700Smckusick 
3027700Smckusick 	/* Create socket from which to read. */
3127700Smckusick 	sock = socket(AF_INET, SOCK_DGRAM, 0);
3227700Smckusick 	if (sock < 0) {
3327700Smckusick 		perror("opening datagram socket");
3427700Smckusick 		exit(-1);
3527700Smckusick 	}
3627700Smckusick 	/* Create name with wildcards. */
3727700Smckusick 	name.sin_family = AF_INET;
3827700Smckusick 	name.sin_addr.s_addr = INADDR_ANY;
3927700Smckusick 	name.sin_port = 0;
4027700Smckusick 	if (bind(sock, &name, sizeof(name))) {
4127700Smckusick 		close(sock);
4227700Smckusick 		perror("binding datagram socket");
4327700Smckusick 	}
4427700Smckusick 	/* Find assigned port value and print it out. */
4527700Smckusick 	length = sizeof(name);
4627700Smckusick 	if (getsockname(sock, &name, &length)) {
4727700Smckusick 		close(sock);
4827700Smckusick 		perror("getting socket name");
4927700Smckusick 	}
5027700Smckusick 	printf("Socket has port #%d\en", ntohs(name.sin_port));
5127700Smckusick 	/* Read from the socket */
5227700Smckusick 	if (read(sock, buf, 1024, 0) < 0)
5327700Smckusick 		perror("receiving datagram packet");
5427700Smckusick 	printf("-->%s\en", buf);
5527700Smckusick 	close(sock);
5627700Smckusick }
57