/* Connection Related Server */ #include #include #include #include #include struct Message_header { struct sockaddr_in mps; struct sockaddr_in mpr; int sessionID; }; /* struct Data{ int sessionID; char msg_type; char msg_size; char data[1024]; }; */ main(int argc, char * argv[]) { int sockfd1; int msgsock; int sockfd2; int length; int rval; int crs_portno; int mpr_portno; struct sockaddr_in crserver; struct sockaddr_in mps; struct sockaddr_in mpr; struct hostent * hp; struct Message_header headr; char frombuf[1024]; char tobuf[1024]; char * mpr_name; sockfd1 = socket(AF_INET, SOCK_STREAM, 0); if(sockfd1 < 0) { perror("Error opening socket\n"); exit(1); } crs_portno = 1027; crserver.sin_family = AF_INET; crserver.sin_addr.s_addr = INADDR_ANY; crserver.sin_port = htons(crs_portno); if(bind(sockfd1, (const struct sockaddr *) &crserver, sizeof(crserver))) { perror("Error binding socket to CRS\n"); exit(1); } length = sizeof(crserver); if(getsockname(sockfd1, (const struct sockaddr *) &crserver, &length)) { perror("Error getting socket name"); exit(1); } printf("CRS is listening to port #: %d\n",ntohs(crserver.sin_port)); listen(sockfd1, 5); while(1) { msgsock = accept(sockfd1, (struct sockaddr *) &mps, &length); if(msgsock < 0){ perror("Accept error"); exit(1); } sockfd2 = socket(AF_INET, SOCK_STREAM, 0); if(sockfd2 < 0) { perror("Error opening socket\n"); exit(1); } if(fork() == 0) { sprintf(tobuf, "CRS is ready to accept message\n"); write(msgsock, tobuf, sizeof(tobuf)-1); /* do{ rval = read(msgsock, &headr, sizeof(headr)); } while(rval < 0); here code to identify the mpr headr.mpr = mpr; populate the mpr structure sprintf(tobuf, "ACK from CRS: Received header\n"); write(msgsock, tobuf, sizeof(tobuf)-1); */ /* read data from mps */ do{ rval = read(msgsock, frombuf, sizeof(frombuf)-1); } while(rval < 0); printf("%s\n", frombuf); /* copy the reply from MPS to tobuf */ strcpy(tobuf, frombuf); mpr_name = "crestone.uccs.edu"; mpr_portno = 1050; hp = gethostbyname(mpr_name); if(hp == 0) { fprintf(stderr, "%s: unknown host\n", mpr_name); exit(2); } memcpy(&mpr.sin_addr, hp->h_addr, hp->h_length); mpr.sin_family = AF_INET; mpr.sin_port = htons(mpr_portno); length = sizeof(mpr); if(connect(sockfd2, (const struct sockaddr *) &mpr, length) < 0) { perror("Error connecting to socket\n"); exit(1); } /* read Ready msg from MPR */ do{ rval = read(sockfd2, frombuf, sizeof(frombuf)-1); } while(rval < 0); printf("%s\n",frombuf); if(write(sockfd2, tobuf, sizeof(tobuf)-1) < 0 ) { perror("Error writing to MPR"); exit(1); } } /* end of child process */ } /* end while */ } /* end main */