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