C_socket_api/client_api.h
2025-02-07 11:00:59 +03:00

60 lines
1.2 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <stdbool.h>
#define PORT 8080
#define BUFFER_SIZE 1024
char BUFFER_REPLY[BUFFER_SIZE] = "";
char* send_command(char* command) {
int sock = 0;
struct sockaddr_in serv_addr;
// Clear buffer
memset(BUFFER_REPLY, 0, BUFFER_SIZE);
// Creating socket file descriptor
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("\n Socket creation error \n");
return "";
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// Converting IPv4 and IPv6 addresses from text to binary form
if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
printf("\nInvalid address/ Address not supported \n");
return "";
}
// Connecting to the server
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
printf("\nConnection Failed \n");
return "";
}
// Sending data to the server
send(sock, command, strlen(command), 0);
// Receiving data from the server
read(sock, BUFFER_REPLY, BUFFER_SIZE);
// Closing the socket
close(sock);
return BUFFER_REPLY;
}
bool cmp(char* reply, char* command) {
if (strcmp(reply, command) == 0) {
return true;
} else {
return false;
}
}