mcping/Connection.cpp

48 lines
1.0 KiB
C++

#include "Connection.h"
#include <sys/socket.h>
#include <arpa/inet.h>
#include <iostream>
#include <unistd.h>
void Connection::p_HandleError(){
std::cout << "an error occured during execution" << std::endl;
switch (error) {
case ErrorTypes::socket_creation:
perror("error while trying to create a file descriptor");
break;
case ErrorTypes::get_ip:
perror("error while trying to get ip");
break;
case ErrorTypes::connect:
perror("error while trying to connect");
break;
default:
std::cerr << "An unknown error occured" << std::endl;
}
}
int Connection::status(){
return static_cast<int>(error);
}
Connection::Connection(std::string server_ip, int port){
fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0){
error = ErrorTypes::socket_creation;
}
in_addr in_a;
if(!inet_aton(server_ip.data(), &in_a)){
error = ErrorTypes::get_ip;
}
sockaddr_in addr({ AF_INET, htons(port), in_a });
if(connect(fd, (sockaddr*) &addr, sizeof(addr)) != 0){
error = ErrorTypes::connect;
}
}
Connection::~Connection(){
close(fd);
}