1 .\" Copyright (c) 1986 Regents of the University of California.
2 .\" All rights reserved.  The Berkeley software License Agreement
3 .\" specifies the terms and conditions for redistribution.
4 .\"
5 .\"	@(#)streamread.c	6.1 (Berkeley) 05/04/86
6 .\"
7 #include <sys/types.h>
8 #include <sys/socket.h>
9 #include <netinet/in.h>
10 #include <netdb.h>
11 #include <stdio.h>
12 #define TRUE 1
13 
14 /*
15  * This program creates a socket and then begins an infinite loop. Each time
16  * through the loop it accepts a connection and prints out messages from it.
17  * When the connection breaks, or a termination message comes through, the
18  * program accepts a new connection.
19  */
20 
21 main()
22 {
23 	int             sock, length;
24 	struct sockaddr_in server;
25 	int             msgsock;
26 	char            buf[1024];
27 	int             rval;
28 	int             i;
29 
30 	/* Create socket */
31 	sock = socket(AF_INET, SOCK_STREAM, 0);
32 	if (sock < 0) {
33 		perror("opening stream socket");
34 		exit(0);
35 	}
36 	/* Name socket using wildcards */
37 	server.sin_family = AF_INET;
38 	server.sin_addr.s_addr = INADDR_ANY;
39 	server.sin_port = 0;
40 	if (bind(sock, &server, sizeof(server))) {
41 		perror("binding stream socket");
42 	}
43 	/* Find out assigned port number and print it out */
44 	length = sizeof(server);
45 	if (getsockname(sock, &server, &length)) {
46 		perror("getting socket name");
47 		exit(0);
48 	}
49 	printf("Socket has port #%d\en", ntohs(server.sin_port));
50 
51 	/* Start accepting connections */
52 	listen(sock, 5);
53 	do {
54 		msgsock = accept(sock, 0, 0);
55 		do {
56 			for (i = 0; i < 1024; i++)
57 				buf[i] = '\e0';
58 			if ((rval = read(msgsock, buf, 1024)) < 0)
59 				perror("reading stream message");
60 			i = 0;
61 			if (rval == 0)
62 				printf("Ending connection\en");
63 			else
64 				printf("-->%s\en", buf);
65 		} while (rval != 0);
66 		close(msgsock);
67 	} while (TRUE);
68 	/*
69 	 * Since this program has an infinite loop, the socket "sock" is
70 	 * never explicitly closed.  However, all sockets will be closed
71 	 * automatically when a process is killed or terminates normally.
72 	 */
73 }
74