finished the first homework? needs testing tho.

This commit is contained in:
Charles Descamps 2025-02-05 14:29:04 -07:00
parent a54d88dc70
commit 0885f44c07

View file

@ -4,6 +4,7 @@
// constants // constants
// timeserver port is 8888 // timeserver port is 8888
#define TIMEPORT "8888" #define TIMEPORT "8888"
#define BUFFER_SIZE 1024
// prototypes // prototypes
@ -11,10 +12,53 @@
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
// initialize program (variables and structs) // 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 // 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 // bind the UDP socket to port 8888 / TIMEPORT
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = INADDR_ANY;
serverAddr.sin_port = 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?) // while loop to see if the "time\r\n" has been received (recv call?)
int clientAddrLen;
int receivedDataLen;
printf("Timeserver listening on port: %d\n", TIMEPORT);
while(quitFlag)
{
// grab the data from the client
receivedDataLen = recvfrom(socketTimeFD, message, BUFFER_SIZE, MSG_WAITALL, &clientAddr, &clientAddrLen);
message[receivedDataLen] = '\0';
// if "time\r\n" is received, then send() back the linux epoch. // if "time\r\n" is received, then send() back the linux epoch.
if(message == "time\r\n")
{
//
char *reply = time(NULL);
sendto(socketTimeFD, reply, strlen(reply), 0, &clientAddr, clientAddrLen);
}
else if(message == "close\r\n" || message == "quit\r\n" || message == "q\r\n")
{
//
quitFlag = false;
}
}
// close the socket
close(socketTimeFD);
// profit??? // profit???
return 0; return 0;
} }