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 .\" @(#)strchkread.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 uses select() to check that someone is trying to connect 16 * before calling accept(). 17 */ 18 19 main() 20 { 21 int sock, length; 22 struct sockaddr_in server; 23 int msgsock; 24 char buf[1024]; 25 int rval; 26 int i; 27 int ready; 28 struct timeval to; 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 ready = 1 << sock; 55 to.tv_sec = 5; 56 select(20, &ready, 0, 0, &to); 57 if (ready) { 58 msgsock = accept(sock, 0, 0); 59 do { 60 for (i = 0; i < 1024; i++) 61 buf[i] = '\e0'; 62 if ((rval = read(msgsock, buf, 1024)) < 0) 63 perror("reading stream message"); 64 i = 0; 65 if (rval == 0) 66 printf("Ending connection\en"); 67 else 68 printf("-->%s\en", buf); 69 } while (rval != 0); 70 close(msgsock); 71 } else 72 printf("Do something else\en"); 73 } while (TRUE); 74 } 75