AAE-CNAS-Labs/Topic-11/server.c
2021-05-19 16:17:49 +02:00

104 lines
3.0 KiB
C

#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
struct TokenizedQuerry {
int left;
char operand;
int right;
};
void handle_arguments(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s PORT\n", argv[0]);
exit(EXIT_FAILURE);
}
}
struct TokenizedQuerry tokenize(const char *querry) {
struct TokenizedQuerry tokenized_querry;
// printf("QUERRY: %s\n", querry);
char left[50], *operand_ptr, right[50];
char valid_operands[4] = {'+', '-', '/', '*'};
for (int i = 0; i < sizeof(valid_operands); ++i) {
operand_ptr = strchr(querry, valid_operands[i]);
if (operand_ptr != NULL) break;
}
if (operand_ptr == NULL) {
fprintf(stderr, "Wrong operand!\n");
exit(EXIT_FAILURE);
}
int left_length = operand_ptr - querry;
strncpy(left, querry, left_length);
strcpy(right, querry + left_length + 1);
// printf("Tokenized: %s %c %s\n", left, *operand_ptr, right);
tokenized_querry.left = strtol(left, NULL, 10);
tokenized_querry.operand = *operand_ptr;
tokenized_querry.right = strtol(right, NULL, 10);
return tokenized_querry;
}
int calculate_TokenizedQuerry(struct TokenizedQuerry expression) {
switch (expression.operand) {
case '+':
return expression.left + expression.right;
case '-':
return expression.left - expression.right;
case '*':
return expression.left * expression.right;
case '/':
return expression.left / expression.right;
}
return 0;
}
void run_server(int port) {
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
fprintf(stderr, "socket: ");
exit(EXIT_FAILURE);
}
struct sockaddr_in serv_addr, client_addr;
memset(&serv_addr, 0, sizeof(serv_addr));
memset(&client_addr, 0, sizeof(client_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
serv_addr.sin_addr.s_addr = INADDR_ANY;
int rv = bind(sockfd, (const struct sockaddr *)&serv_addr, sizeof(serv_addr));
if (rv < 0) {
fprintf(stderr, "bind: ");
exit(EXIT_FAILURE);
}
size_t buffer_size = 100;
char buffer[buffer_size];
memset(&buffer, 0, buffer_size);
socklen_t client_addr_len;
struct TokenizedQuerry tokenized_querry;
while (1) {
rv = recvfrom(sockfd, buffer, buffer_size, 0, (struct sockaddr *)&client_addr, &client_addr_len);
tokenized_querry = tokenize(buffer);
int result = calculate_TokenizedQuerry(tokenized_querry);
memset(&buffer, 0, buffer_size);
snprintf(buffer, buffer_size, "%d", result);
rv = sendto(sockfd, buffer, sizeof(buffer), 0, (const struct sockaddr *)&client_addr, sizeof(client_addr));
memset(&buffer, 0, sizeof(buffer));
}
}
int main(int argc, char *argv[]) {
handle_arguments(argc, argv);
run_server(strtol(argv[1], NULL, 10));
return 0;
}