Add ability to compare IPv6 addresses

This commit is contained in:
Kawe Mazidjatari 2023-04-16 11:55:57 +02:00
parent 8bf105b072
commit c354d7ae02
4 changed files with 55 additions and 0 deletions

View File

@ -28,6 +28,9 @@ public:
netadrtype_t GetType(void) const;
uint16_t GetPort(void) const;
bool CompareAdr(const CNetAdr& other) const;
bool ComparePort(const CNetAdr& other) const;
const char* ToString(bool onlyBase = false) const;
void ToString(char* pchBuffer, size_t unBufferSize, bool onlyBase = false) const;
void ToAdrinfo(addrinfo* pHint) const;

View File

@ -1078,6 +1078,25 @@ string Format(const char* szFormat, ...)
return result;
}
///////////////////////////////////////////////////////////////////////////////
// For comparing two IPv6 addresses.
int CompareIPv6(const IN6_ADDR& ipA, const IN6_ADDR& ipB)
{
// Return 0 if ipA == ipB, -1 if ipA < ipB and 1 if ipA > ipB.
for (int i = 0; i < 16; ++i)
{
if (ipA.s6_addr[i] < ipB.s6_addr[i])
{
return -1;
}
else if (ipA.s6_addr[i] > ipB.s6_addr[i])
{
return 1;
}
}
return 0;
}
///////////////////////////////////////////////////////////////////////////////
// For obtaining a duration from a certain interval.
std::chrono::nanoseconds IntervalToDuration(const float flInterval)

View File

@ -109,6 +109,10 @@ Iter MaxElementABS(Iter first, Iter last)
return ExtremeElementABS(first, last, std::greater<>());
}
/////////////////////////////////////////////////////////////////////////////
// Net
int CompareIPv6(const IN6_ADDR& ipA, const IN6_ADDR& ipB);
/////////////////////////////////////////////////////////////////////////////
// Time
std::chrono::nanoseconds IntervalToDuration(const float flInterval);

View File

@ -76,6 +76,35 @@ uint16_t CNetAdr::GetPort(void) const
return port;
}
//////////////////////////////////////////////////////////////////////
// Compares two addresses.
//////////////////////////////////////////////////////////////////////
bool CNetAdr::CompareAdr(const CNetAdr& other) const
{
if (type != other.type)
{
return false;
}
if (type == netadrtype_t::NA_LOOPBACK)
{
return true;
}
if (type == netadrtype_t::NA_IP)
{
return (CompareIPv6(adr, other.adr) == 0);
}
return false;
}
//////////////////////////////////////////////////////////////////////
// Compares two ports.
//////////////////////////////////////////////////////////////////////
bool CNetAdr::ComparePort(const CNetAdr& other) const
{
return port == other.port;
}
//////////////////////////////////////////////////////////////////////
// Convert address to string.
//////////////////////////////////////////////////////////////////////