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.2 (Berkeley) 05/08/86 6 .\" 7 #include <sys/types.h> 8 #include <sys/socket.h> 9 #include <sys/time.h> 10 #include <netinet/in.h> 11 #include <netdb.h> 12 #include <stdio.h> 13 #define TRUE 1 14 15 /* 16 * This program uses select() to check that someone is trying to connect 17 * before calling accept(). 18 */ 19 20 main() 21 { 22 int sock, length; 23 struct sockaddr_in server; 24 int msgsock; 25 char buf[1024]; 26 int rval; 27 fd_set 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(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 FD_ZERO(&ready); 56 FD_SET(sock, &ready); 57 to.tv_sec = 5; 58 if (select(sock + 1, &ready, 0, 0, &to) < 0) { 59 perror("select"); 60 continue; 61 } 62 if (FD_ISSET(sock, &ready)) { 63 msgsock = accept(sock, (struct sockaddr *)0, (int *)0); 64 if (msgsock == -1) 65 perror("accept"); 66 else do { 67 bzero(buf, sizeof(buf)); 68 if ((rval = read(msgsock, buf, 1024)) < 0) 69 perror("reading stream message"); 70 else if (rval == 0) 71 printf("Ending connection\en"); 72 else 73 printf("-->%s\en", buf); 74 } while (rval > 0); 75 close(msgsock); 76 } else 77 printf("Do something else\en"); 78 } while (TRUE); 79 } 80