feat(IPAddress): add functions returning addres as raw bytes

This commit is contained in:
Alex Fabijanic 2021-05-25 21:54:42 +02:00
parent 03d3251cd1
commit 710b2c51cc
2 changed files with 49 additions and 1 deletions

View File

@ -24,6 +24,7 @@
#include "Poco/AutoPtr.h"
#include "Poco/Exception.h"
#include <vector>
#include <array>
#include <ostream>
@ -56,6 +57,13 @@ class Net_API IPAddress
public:
using List = std::vector<IPAddress>;
using RawIP = std::vector<unsigned char>;
static const unsigned IPv4Size = sizeof(in_addr);
static const unsigned IPv6Size = sizeof(in6_addr);
using RawIPv4 = std::array<unsigned char, IPv4Size>;
using RawIPv6 = std::array<unsigned char, IPv6Size>;
// The following declarations keep the Family type
// backwards compatible with the previously used
// enum declaration.
@ -122,7 +130,11 @@ public:
IPAddress& operator = (const IPAddress& addr);
/// Assigns an IPAddress.
std::vector<unsigned char> toBytes() const;
bool isV4() const;
bool isV6() const;
RawIPv4 toV4Bytes() const;
RawIPv6 toV6Bytes() const;
RawIP toBytes() const;
Family family() const;
/// Returns the address family (IPv4 or IPv6) of the address.
@ -386,6 +398,19 @@ private:
//
// inlines
//
inline bool IPAddress::isV4() const
{
return family() == IPv4;
}
inline bool IPAddress::isV6() const
{
return family() == IPv6;
}
inline IPAddress::Ptr IPAddress::pImpl() const
{
if (_pImpl) return _pImpl;

View File

@ -573,6 +573,28 @@ IPAddress IPAddress::broadcast()
}
IPAddress::RawIPv4 IPAddress::toV4Bytes() const
{
if (family() != IPv4)
throw Poco::InvalidAccessException(Poco::format("IPAddress::toV4Bytes(%d)", (int)family()));
RawIPv4 bytes;
std::memcpy(&bytes[0], addr(), IPv4Size);
return bytes;
}
IPAddress::RawIPv6 IPAddress::toV6Bytes() const
{
if (family() != IPv6)
throw Poco::InvalidAccessException(Poco::format("IPAddress::toV6Bytes(%d)", (int)family()));
RawIPv6 bytes;
std::memcpy(&bytes[0], addr(), IPv6Size);
return bytes;
}
std::vector<unsigned char> IPAddress::toBytes() const
{
std::size_t sz = 0;
@ -593,6 +615,7 @@ std::vector<unsigned char> IPAddress::toBytes() const
default:
throw Poco::IllegalStateException(Poco::format("IPAddress::toBytes(%d)", (int)family()));
}
bytes.resize(sz);
std::memcpy(&bytes[0], ptr, sz);
return bytes;
}