/* server for inet stream demo */ /* cmd format: inetstr */ #include #include #include #include #include #define TRUE 1 /* this program creates a socket and then begin an infinite loop. Each time * through the loop, it accepts a connection and prints out messages form it. * When the connection breaks, or a termination messgage come through, the * program accepts a new connection. */ main() { int sock; int length; struct sockaddr_in server; int msgsock; char buf[1024]; int rval; int i; /* create socket from which to read */ sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) { perror("opening stream socket"); exit(1); } /* create name structure with wildcard using INADDR_ANY */ server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = 0; /* port no. < 1024 IPPORT_RESERVED is for privillege process */ /* here just initialized it, it will be assigned value after call */ /* getsockname() */ if (bind(sock, &server, sizeof(server))) { perror("binding server to datagram socket"); exit(1); } /* Find assigned port value and print out. */ printf("before getsockname socket has port #%d\n", ntohs(server.sin_port)); length = sizeof(server); if (getsockname(sock, &server, &length)) { perror("getting socket name"); exit(1); } printf("socket has port #%d\n", ntohs(server.sin_port)); /* start accepting connections */ listen(sock, 5); do { msgsock = accept(sock, 0, 0); if (msgsock == -1) perror("accept"); else do { memset(buf, 0, sizeof(buf)); /* in berkeley unix, it is bzero(buf, sizeof(buf)) */ if ((rval = read(msgsock, buf, 1024)) < 0) perror("reading stream message"); i = 0; if (rval == 0) printf("Ending connection\n"); else printf("-->%s\n", buf); } while (rval != 0); close(msgsock); } while (TRUE); }