lokinet/llarp/net/ip_address.cpp

137 lines
2.3 KiB
C++
Raw Normal View History

2020-05-08 17:23:21 +00:00
#include <net/ip_address.hpp>
#include <net/net.hpp>
2020-05-08 17:23:21 +00:00
namespace llarp
{
IpAddress::IpAddress(std::string_view str)
{
setAddress(str);
2020-05-08 17:23:21 +00:00
}
IpAddress::IpAddress(std::string_view str, std::optional<uint16_t> port)
{
setAddress(str, port);
2020-05-08 17:23:21 +00:00
}
IpAddress::IpAddress(const SockAddr& addr)
{
m_ipAddress = addr.toString();
uint16_t port = addr.getPort();
if (port > 0)
m_port = port;
m_empty = addr.isEmpty();
2020-05-08 17:23:21 +00:00
}
IpAddress&
2020-05-08 17:23:21 +00:00
IpAddress::operator=(const sockaddr& other)
{
SockAddr addr(other);
m_ipAddress = addr.toString();
uint16_t port = addr.getPort();
if (port > 0)
m_port = port;
m_empty = addr.isEmpty();
return *this;
2020-05-08 17:23:21 +00:00
}
std::optional<uint16_t>
IpAddress::getPort() const
{
return m_port;
2020-05-08 17:23:21 +00:00
}
void
IpAddress::setPort(std::optional<uint16_t> port)
{
m_port = port;
2020-05-08 17:23:21 +00:00
}
void
IpAddress::setAddress(std::string_view str)
{
SockAddr addr;
addr.fromString(str);
m_ipAddress = std::string(str);
uint16_t port = addr.getPort();
if (port > 0)
m_port = port;
m_empty = addr.isEmpty();
2020-05-08 17:23:21 +00:00
}
void
IpAddress::setAddress(std::string_view str, std::optional<uint16_t> port)
{
SockAddr addr;
addr.fromString(str);
m_ipAddress = std::string(str);
m_port = port;
m_empty = addr.isEmpty();
2020-05-08 17:23:21 +00:00
}
bool
IpAddress::isIPv4()
{
throw std::runtime_error("FIXME - IpAddress::isIPv4()");
2020-05-08 17:23:21 +00:00
}
bool
IpAddress::isEmpty() const
{
return m_empty;
2020-05-08 17:23:21 +00:00
}
SockAddr
IpAddress::createSockAddr() const
{
SockAddr addr(m_ipAddress);
if (m_port)
addr.setPort(*m_port);
return addr;
2020-05-08 17:23:21 +00:00
}
bool
IpAddress::isBogon() const
{
SockAddr addr(m_ipAddress);
const sockaddr_in6* addr6 = addr;
2020-05-15 18:07:22 +00:00
const uint8_t* raw = addr6->sin6_addr.s6_addr;
return IsIPv4Bogon(ipaddr_ipv4_bits(raw[12], raw[13], raw[14], raw[15]));
2020-05-08 17:23:21 +00:00
}
std::string
IpAddress::toString() const
{
return m_ipAddress; // TODO: port
2020-05-08 17:23:21 +00:00
}
bool
IpAddress::operator<(const IpAddress& other) const
{
return createSockAddr() < other.createSockAddr();
2020-05-08 17:23:21 +00:00
}
bool
IpAddress::operator==(const IpAddress& other) const
{
return createSockAddr() == other.createSockAddr();
2020-05-08 17:23:21 +00:00
}
std::ostream&
operator<<(std::ostream& out, const IpAddress& address)
{
out << address.toString();
return out;
2020-05-08 17:23:21 +00:00
}
} // namespace llarp