/* Stream server, by Dan Fraser */ #include #include #include #include #include #include #include #include #include #include #include "dbase.h" #define TRUE 1 int main(void) { int sock; /* socket handle. */ int length; /* length of a sockaddr structure. */ int msgsock; /* temporary socket for current connection. */ int rval; /* return value from read() */ struct sockaddr_in server,remote; /* address structures */ char buf[1024]; /* input/output buffer */ char descript[501]; /* description buffer. */ /* create a socket */ sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) { printf("error opening stream socket.\n"); exit(1); } printf("socket opened.\n"); /* set up the address information. */ server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port=0; /* bind the address to the socket. */ if (bind(sock,(struct sockaddr*)&server, sizeof(server))) { printf("error binding stream socket.\n"); exit(1); } printf("socket bound.\n"); /* get the socket name */ if (getsockname(sock, (struct sockaddr*) &server, &length)) { printf("error getting socket name.\n"); exit(1); } printf("got socket name.\n"); /* listen to the socket for connection attempts */ listen(sock,5); do { /* wait for a connection */ printf("waiting for connection on port %d.\n",server.sin_port); msgsock = accept(sock,(struct sockaddr*) &remote,&length); /* got a connection, deal with it */ printf("got connection from host %s.\n",inet_ntoa(remote.sin_addr)); if (msgsock == -1) { printf("error accepting connection.\n"); } else do { /* clear the buffer */ bzero(buf,sizeof(buf)); /* read the data into the buffer */ if ((rval = read(msgsock,buf,1024)) < 0) printf("error reading stream message.\n"); if (rval == 0) printf("ending connection.\n"); else { /* print out what we've received and act on it */ printf("-->%s\n",buf); printf("%s\n",outval(buf,descript)); if (write(msgsock,descript,strlen(descript)) < 0) { printf("error sending reply!\n"); exit(1); } } /* clean up if they've hung up on us */ } while ((rval != 0) && (strncmp(buf,"END",3)!=0)); printf("terminating connection.\n"); close(msgsock); } while (TRUE); }