/////////////////////////////////////// // simple unix server to be used in // synchronizing client clocks // // main algorithm: // James Maxlow // // generic socket processes (modified): // RPC Programming Nutshell /////////////////////////////////////// #include #include #include #include #include #include #include #include #define PORT 9090 int main() { ////////////////////// /* socket variables */ ////////////////////// struct sockaddr_in sin; struct sockaddr_in pin; int sd, sd_current, cc, fromlen, tolen; int addrlen; //////////////////////////////////////////////////// /* used to hold and send server's time as strings */ //////////////////////////////////////////////////// char timereplysec[sizeof(long)*8+3]; char timereplyusec[sizeof(long)*8+3]; char timereply[(sizeof(long)*8+3)*2+3] = ""; int j = 0; timeval stime; /* server's time struct in seconds and microseconds */ char messagereq[4]; /* holds client junk request */ ////////////////////////////// /* generic socket processes */ ////////////////////////////// /* get an internet domain socket */ if ((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); } /* complete the socket structure */ memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = INADDR_ANY; sin.sin_port = htons(PORT); /* bind the socket to the port number */ if (bind(sd, (struct sockaddr *) &sin, sizeof(sin)) == -1) { perror("bind"); exit(1); } /* show that we are willing to listen */ if (listen(sd, 5) == -1) { perror("listen"); exit(1); } /* wait for a client to talk to us */ if ((sd_current = accept(sd, (struct sockaddr *) &pin, &addrlen)) == -1) { perror("accept"); exit(1); } /* get a message from the client */ if (recv(sd_current, messagereq, 4, 0) == -1) { perror("recv"); exit(1); } ///////////////////////////////////////////////////////////////////// /* get server time, change to strings, combine to one string, send */ ///////////////////////////////////////////////////////////////////// gettimeofday(&stime,0); sprintf(timereplysec, "%ld", stime.tv_sec); sprintf(timereplyusec, "%ld", stime.tv_usec); strcat(timereply, timereplysec); strcat(timereply, " - "); strcat(timereply, timereplyusec); /* acknowledge the message, reply with time */ if (send(sd_current, timereply, (sizeof(long)*8+3)*2+3, 0) == -1) { perror("send"); exit(1); } /* close up both sockets */ shutdown(sd_current, 2); shutdown(sd, 2); /* give client a chance to properly shutdown */ sleep(1); } //end main