/* 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", 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); } main(argc, argv) int argc; char *argv[]; { int sock; int length; struct sockaddr_in server; struct sockaddr_in from; int msgsock; int debug = 0; int forkflag = 1; extern char *optarg; extern int optind; int option_exist = 0; int c; /* process command line args */ while ((c=getopt(argc,argv,"df")) != EOF) { option_exist = 1; switch(c) { case 'd': debug = 1; if (debug) printf("turn on debug mode.\n"); break; case 'f': forkflag = 1; printf("turn on fork processing mode.\n"); break; case '?': help_msg(); exit (1); default: fprintf (stderr, "unrecognized arg >%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"); exit(2);} if (forkflag) { if (fork()==0) { close(sock); doit(msgsock); exit(0); } } else { doit(msgsock); } close(msgsock); } while (TRUE); }