78 lines
1.9 KiB
C++
78 lines
1.9 KiB
C++
#include "networking.h"
|
|
|
|
#include <cstdint>
|
|
#include <memory>
|
|
#include <optional>
|
|
#include <stdexcept>
|
|
#include <string>
|
|
#include <string_view>
|
|
#include <gccore.h>
|
|
#include <network.h>
|
|
|
|
|
|
bool Networking::_connected = false;
|
|
|
|
bool Networking::init() noexcept
|
|
{
|
|
if (!Networking::_connected)
|
|
{
|
|
int32_t ret = if_config(
|
|
_ip_address,
|
|
_netmask,
|
|
_gateway,
|
|
TRUE,
|
|
20
|
|
);
|
|
|
|
if (ret >= 0)
|
|
Networking::_connected = true;
|
|
}
|
|
|
|
return Networking::_connected;
|
|
}
|
|
|
|
int32_t Networking::create_socket(uint8_t type)
|
|
{
|
|
if (type != SOCK_STREAM && type != SOCK_DGRAM)
|
|
throw std::invalid_argument("Unsupported socket type.");
|
|
|
|
int32_t sock = net_socket(AF_INET, type, IPPROTO_IP);
|
|
if (sock == INVALID_SOCKET)
|
|
throw std::runtime_error("Could not create socket.");
|
|
|
|
return sock;
|
|
}
|
|
|
|
std::unique_ptr<sockaddr_in> Networking::create_host(uint16_t port) noexcept
|
|
{
|
|
auto server = std::make_unique<sockaddr_in>();
|
|
server->sin_family = AF_INET;
|
|
server->sin_port = htons(port);
|
|
server->sin_addr.s_addr = INADDR_ANY;
|
|
return server;
|
|
}
|
|
|
|
std::unique_ptr<sockaddr_in> Networking::create_dest(std::string_view ip_address, uint16_t port) noexcept
|
|
{
|
|
auto server = std::make_unique<sockaddr_in>();
|
|
server->sin_family = AF_INET;
|
|
server->sin_port = htons(port);
|
|
inet_aton(ip_address.data(), &(server->sin_addr));
|
|
return server;
|
|
}
|
|
|
|
std::optional<std::string> Networking::get_ip_address() noexcept
|
|
{
|
|
return Networking::_connected ? std::optional(std::string(_ip_address)) : std::nullopt;
|
|
}
|
|
|
|
std::optional<std::string> Networking::get_netmask() noexcept
|
|
{
|
|
return Networking::_connected ? std::optional(std::string(_netmask)) : std::nullopt;
|
|
}
|
|
|
|
std::optional<std::string> Networking::get_gateway() noexcept
|
|
{
|
|
return Networking::_connected ? std::optional(std::string(_gateway)) : std::nullopt;
|
|
}
|