82 lines
No EOL
2.4 KiB
C
82 lines
No EOL
2.4 KiB
C
// header files
|
|
#include "timeserver.h"
|
|
|
|
// constants
|
|
// timeserver port is 8888
|
|
#define TIMEPORT 8888
|
|
#define BUFFER_SIZE 1024
|
|
|
|
// prototypes
|
|
|
|
// main function
|
|
int main(int argc, char **argv)
|
|
{
|
|
// initialize program (variables and structs)
|
|
bool quitFlag = true;
|
|
int socketTimeFD;
|
|
char message[BUFFER_SIZE];
|
|
struct sockaddr_in serverAddr, clientAddr;
|
|
memset(&serverAddr, 0, sizeof(serverAddr));
|
|
memset(&clientAddr, 0, sizeof(clientAddr));
|
|
// define a UDP socket
|
|
socketTimeFD = socket(AF_INET, SOCK_DGRAM, 0);
|
|
if(socketTimeFD < 0)
|
|
{
|
|
printf("Unable to create the socket.");
|
|
return -1;
|
|
}
|
|
// bind the UDP socket to port 8888 / TIMEPORT
|
|
serverAddr.sin_family = AF_INET;
|
|
serverAddr.sin_addr.s_addr = INADDR_ANY;
|
|
serverAddr.sin_port = htons(TIMEPORT);
|
|
int bindCheck = bind(socketTimeFD, &serverAddr, sizeof(serverAddr));
|
|
if(bindCheck < 0)
|
|
{
|
|
printf("Unable to bind the socket to the port or address.\n Is either in use?");
|
|
return -1;
|
|
}
|
|
// while loop to see if the "time\r\n" has been received (recv call?)
|
|
printf("Timeserver listening on port: %d\n", TIMEPORT);
|
|
while(quitFlag)
|
|
{
|
|
int clientAddrLen;
|
|
int receivedDataLen;
|
|
// grab the data from the client
|
|
receivedDataLen = recvfrom(socketTimeFD, message, BUFFER_SIZE, MSG_WAITALL, &clientAddr, &clientAddrLen);
|
|
message[receivedDataLen] = '\0';
|
|
printf("Message rec: %s", message);
|
|
// if "time\r\n" is received, then send() back the linux epoch.
|
|
if(strcmp(message, "time\n") == 0)
|
|
{
|
|
//
|
|
char *reply;
|
|
sprintf(reply, "%d", time(NULL));
|
|
// char *reply = time(NULL);
|
|
// char *reply = "Replied";
|
|
sendto(socketTimeFD, (const char *)reply, strlen(reply), 0, (const struct sockaddr *) &clientAddr, clientAddrLen);
|
|
}
|
|
else if(strcmp(message, "close") == 0 || strcmp(message, "quit") == 0 || strcmp(message, "q") == 0)
|
|
{
|
|
//
|
|
printf("\nServer received close.\n");
|
|
quitFlag = false;
|
|
}
|
|
}
|
|
// close the socket
|
|
close(socketTimeFD);
|
|
// profit???
|
|
return 0;
|
|
}
|
|
|
|
// function definitions
|
|
|
|
/*
|
|
Name: ???
|
|
Process: ???
|
|
Function Input/Parameters: ???
|
|
Function Output/Parameters: ???
|
|
Function Output/Returned: ???
|
|
Device Input/Device: ???
|
|
Device Output/Device: ???
|
|
Dependencies: ???
|
|
*/ |