/* server for inet stream demo */ /* cmd format: istr */ #include #include #include #include #include #define TRUE 1 #define MAXLINE 256 /* this program creates a socket and then begin an infinite loop. Each time * through the loop, it accepts a connection, prints out messages from it, * and then ask for reply message from the user. * When the connection breaks, or a termination messgage come through, the * program accepts a new connection. */ void printsockaddr(struct sockaddr_in *arg) { struct hostent *hp; printf(" sockaddr_in: "); printf("Domain=%d, ", arg->sin_family); hp=gethostbyaddr((const char *)&(arg->sin_addr), sizeof(arg->sin_addr), AF_INET); printf("Hostname=%s, ", hp->h_name); printf("Port=%d, ", ntohs(arg->sin_port)); printf("Address=%s,\n", inet_ntoa(arg->sin_addr)); } getline(s, lim) char s[]; int lim; { int c, i; for (i=0; i%s<\n", optarg); help_msg(); exit (1); } } /* 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, 1); do { msgsock = accept(sock, (struct sockaddr *)&from, &length); if (debug) { printf("accept request from \n"); printsockaddr(&from); } if (msgsock == -1) perror("accept"); else do { bzero(buf, sizeof(buf)); if ((rval = read(msgsock, buf, 1024)) < 0) perror("reading stream message"); i = 0; if (rval == 0) { printf("Ending connection\n"); break; } else printf("rcvd msg-->%s\n", buf); printf("What is your reply (\"$\" to break connection)?"); if ((rval=getline(fromBuf, 1024)) <= 0) break; if (fromBuf[0] == '$') { rval = 0; break; } /* send back reply */ if (write(msgsock, fromBuf, strlen(fromBuf)) < 0) perror("writing on stream socket"); } while (rval != 0); close(msgsock); } while (TRUE); }