h804tun/tundev.h

73 lines
1.7 KiB
C++

#pragma once
#include <linux/if_ether.h>
#include <linux/if_packet.h>
#include <array>
#include <string>
namespace h804::tun {
constexpr int TUN_MTU = 1450;
class TunnelDevice {
int tun_fd;
std::string name;
public:
TunnelDevice(const std::string& local_ip, const std::string& local_netmask);
TunnelDevice(const TunnelDevice&) = delete;
TunnelDevice& operator=(const TunnelDevice&) = delete;
virtual ~TunnelDevice();
void write(const std::array<uint8_t, TUN_MTU>& buf, size_t length) const;
size_t read(std::array<uint8_t, TUN_MTU>& buf) const;
const std::string& get_name() const;
};
constexpr short ETH_TYPE = ETH_P_802_EX1;
class macaddr_t : public std::array<uint8_t, 6> {
public:
macaddr_t();
macaddr_t(const std::string& str);
macaddr_t(const uint8_t octets[6]);
macaddr_t(const sockaddr_ll& linux_addr);
sockaddr_ll to_linux(int if_idx) const;
std::string to_string() const;
operator std::string() const;
bool operator==(const macaddr_t& other) const;
};
class EthSocket {
int eth_fd;
int if_index;
macaddr_t source_mac;
public:
EthSocket(const std::string& if_name);
EthSocket(const EthSocket&) = delete;
EthSocket& operator=(const EthSocket&) = delete;
virtual ~EthSocket();
void write(const std::array<uint8_t, TUN_MTU>& buf, size_t len, const macaddr_t& to) const;
size_t read(std::array<uint8_t, TUN_MTU>& buf, macaddr_t& from_mac) const;
const macaddr_t& get_source_mac() const;
};
} // namespace h804::tun
namespace std {
template <>
struct hash<h804::tun::macaddr_t> {
std::size_t operator()(const h804::tun::macaddr_t& m) const {
return m[0] + m[1] + m[2] + m[3] + m[4] + m[5];
}
};
} // namespace std