85 lines
2.3 KiB
C
85 lines
2.3 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;
|
||
|
|
||
|
return tokenized_querry;
|
||
|
}
|
||
|
|
||
|
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);
|
||
|
}
|
||
|
|
||
|
char buffer[100];
|
||
|
memset(&buffer, 0, sizeof(buffer));
|
||
|
socklen_t client_addr_len;
|
||
|
struct TokenizedQuerry tokenized_querry;
|
||
|
|
||
|
while (1) {
|
||
|
rv = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&client_addr, &client_addr_len);
|
||
|
tokenized_querry = tokenize(buffer);
|
||
|
|
||
|
//rv = sendto(sockfd, response, sizeof(response), 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;
|
||
|
}
|