ClienteTFG/conexion.cpp

49 lines
1.3 KiB
C++
Raw Normal View History

2020-05-08 12:42:02 +02:00
#include "conexion.h"
#include <arpa/inet.h>
#include <sys/socket.h>
#include <memory.h>
#include <unistd.h>
#define CHK_ERR(err,s) if ((err)==-1) { perror(s); exit(1); }
conexion::conexion(config_reader &conf)
{
config=&conf;
int err;
struct sockaddr_in server_address;
this->fd = socket (AF_INET, SOCK_STREAM, 0);
CHK_ERR(this->fd, "error initial conexion")
std::string port;
if(!this->config->get_param("port",port)){
perror("error to acces the port in the config");
}
std::string host;
if(!this->config->get_param("host",host)){
perror("error to accest to the host in the config");
}
memset(&server_address, 0, sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = inet_addr (host.data()); /* Server IP */
server_address.sin_port = htons (atoi(port.data())); /* Server Port number */
err = connect(this->fd, (struct sockaddr*) &server_address,
sizeof(server_address));
CHK_ERR(err, "error in connexion")
}
ssize_t conexion::read_string(std::string &entrada, int size){
char* buffer = new char[size+1];
ssize_t ret=read(this->fd,buffer,size);
buffer[ret]='\0';
entrada = buffer;
return ret;
}
ssize_t conexion::write_string(std::string entrada){
return write(this->fd,entrada.data(),entrada.size());
}