You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
76 lines
1.7 KiB
C++
76 lines
1.7 KiB
C++
#include "easysock.hpp"
|
|
#include <iostream>
|
|
#include <cerrno>
|
|
#include "exception_consts.hpp"
|
|
/*
|
|
Server class - Defines a TCP/UDP server.
|
|
- The constructor takes in a **local** address and port, on which the server listens.
|
|
*/
|
|
|
|
class Server {
|
|
private:
|
|
int ip_ver;
|
|
char protocol;
|
|
int port;
|
|
int sock_fd;
|
|
std::string address;
|
|
|
|
void create_socket() {
|
|
struct sockaddr* dest = (struct sockaddr *)malloc(sizeof(struct sockaddr));
|
|
this->sock_fd = create_local(this->ip_ver, this->protocol, this->address.data(), this->port, dest);
|
|
if (sock_fd < 0) {
|
|
if (sock_fd * -1 == EADDRNOTAVAIL) {
|
|
throw EXCEPT_ADDRNOTAVAIL;
|
|
}
|
|
}
|
|
}
|
|
|
|
public:
|
|
Server() {}
|
|
|
|
Server(int ip_ver, char protocol, const char* address, int port) {
|
|
/* Error checking */
|
|
if (ip_ver != 4 && ip_ver != 6) {
|
|
throw std::invalid_argument("Invalid IP address type");
|
|
}
|
|
if (port < 1024 || port > 65535) {
|
|
throw std::invalid_argument("Invalid port");
|
|
}
|
|
if (protocol != 'T' && protocol != 'U') {
|
|
throw std::invalid_argument("Invalid protocol");
|
|
}
|
|
|
|
this->ip_ver = ip_ver;
|
|
this->protocol = protocol;
|
|
this->port = port;
|
|
this->address = std::string(address);
|
|
|
|
/* Check to see if the given IP address matches the given ip_ver */
|
|
if ((check_ip_ver(address) == 4 && ip_ver == 6) || (check_ip_ver(address) == 6 && ip_ver == 4)) {
|
|
throw std::invalid_argument("Invalid IP address for given type.");
|
|
}
|
|
|
|
try {
|
|
create_socket();
|
|
} catch (int e) {
|
|
throw;
|
|
}
|
|
}
|
|
|
|
|
|
std::string recvAll() {
|
|
std::string string = std::string();
|
|
char* buffer = (char *)malloc(100);
|
|
while (recv(this->getSockFD(), buffer, 100, 0) != 0) {
|
|
string.append(std::string(buffer));
|
|
}
|
|
|
|
return string;
|
|
}
|
|
|
|
int getSockFD() {
|
|
return sock_fd;
|
|
}
|
|
|
|
};
|