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.2 (Berkeley) 05/08/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(1); 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 exit(1); 43 } 44 /* Find out assigned port number and print it out */ 45 length = sizeof(server); 46 if (getsockname(sock, &server, &length)) { 47 perror("getting socket name"); 48 exit(1); 49 } 50 printf("Socket has port #%d\en", ntohs(server.sin_port)); 51 52 /* Start accepting connections */ 53 listen(sock, 5); 54 do { 55 msgsock = accept(sock, 0, 0); 56 if (msgsock == -1) 57 perror("accept"); 58 else do { 59 bzero(buf, sizeof(buf)); 60 if ((rval = read(msgsock, buf, 1024)) < 0) 61 perror("reading stream message"); 62 i = 0; 63 if (rval == 0) 64 printf("Ending connection\en"); 65 else 66 printf("-->%s\en", buf); 67 } while (rval != 0); 68 close(msgsock); 69 } while (TRUE); 70 /* 71 * Since this program has an infinite loop, the socket "sock" is 72 * never explicitly closed. However, all sockets will be closed 73 * automatically when a process is killed or terminates normally. 74 */ 75 } 76