1 .\" Copyright (c) 1986, 1993 2 .\" The Regents of the University of California. All rights reserved. 3 .\" 4 .\" %sccs.include.redist.roff% 5 .\" 6 .\" @(#)strchkread.c 8.1 (Berkeley) 06/08/93 7 .\" 8 #include <sys/types.h> 9 #include <sys/socket.h> 10 #include <sys/time.h> 11 #include <netinet/in.h> 12 #include <netdb.h> 13 #include <stdio.h> 14 #define TRUE 1 15 16 /* 17 * This program uses select() to check that someone is trying to connect 18 * before calling accept(). 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 fd_set ready; 29 struct timeval to; 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 FD_ZERO(&ready); 57 FD_SET(sock, &ready); 58 to.tv_sec = 5; 59 if (select(sock + 1, &ready, 0, 0, &to) < 0) { 60 perror("select"); 61 continue; 62 } 63 if (FD_ISSET(sock, &ready)) { 64 msgsock = accept(sock, (struct sockaddr *)0, (int *)0); 65 if (msgsock == -1) 66 perror("accept"); 67 else do { 68 bzero(buf, sizeof(buf)); 69 if ((rval = read(msgsock, buf, 1024)) < 0) 70 perror("reading stream message"); 71 else if (rval == 0) 72 printf("Ending connection\en"); 73 else 74 printf("-->%s\en", buf); 75 } while (rval > 0); 76 close(msgsock); 77 } else 78 printf("Do something else\en"); 79 } while (TRUE); 80 } 81