Skip to content

Commit

Permalink
Add IO::Networking::IpAddress::FromIpv4Uint32
Browse files Browse the repository at this point in the history
  • Loading branch information
0blu committed Aug 27, 2024
1 parent 8c3f71f commit 7c571cd
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
17 changes: 15 additions & 2 deletions src/shared/IO/Networking/IpAddress.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,19 @@
#include <sstream>
#include "IpAddress.h"

IO::Networking::IpAddress IO::Networking::IpAddress::FromIpv4Uint32(uint32_t ip)
{
IpAddress result;
result.m_address.type = Type::IPv4;
result.m_address.ipv4 = {
uint8_t((ip >> (3*8)) & 0xFF),
uint8_t((ip >> (2*8)) & 0xFF),
uint8_t((ip >> (1*8)) & 0xFF),
uint8_t((ip >> (0*8)) & 0xFF),
};
return result;
}

nonstd::optional<IO::Networking::IpAddress> IO::Networking::IpAddress::TryParseFromString(std::string const& ipAddressString)
{
IpAddress result;
Expand All @@ -20,9 +33,10 @@ nonstd::optional<IO::Networking::IpAddress> IO::Networking::IpAddress::TryParseF
const char* tmpStartPtr = tmpLastEndPtr;
tmpLastEndPtr = fixEndPtr;

// Parse number
int64_t segment = std::strtoll(tmpStartPtr, const_cast<char **>(&tmpLastEndPtr), 10);
if (segment < 0 || segment > 255)
return nonstd::nullopt;
return nonstd::nullopt; // invalid number range, only [0..255] is valid

if (i != (result.m_address.ipv4.size() - 1))
{ // We should not be at the end, and the next character should be a dot
Expand Down Expand Up @@ -128,4 +142,3 @@ uint32_t IO::Networking::IpAddress::_getInternalIPv4ReprAsUint32() const
| (m_address.ipv4[2] << (1*8))
| (m_address.ipv4[3] << (0*8));
}

4 changes: 2 additions & 2 deletions src/shared/IO/Networking/IpAddress.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ namespace IO { namespace Networking
public:
enum class Type { IPv4, IPv6 };

static IpAddress FromIpv4Uint32(uint32_t ip);
static nonstd::optional<IpAddress> TryParseFromString(std::string const& ipAddressString);

/// IPv4 Format: 255.255.255.255
Expand All @@ -21,8 +22,7 @@ namespace IO { namespace Networking
Type getType() const;

uint32_t _getInternalIPv4ReprAsUint32() const;

private:
private:
struct
{
Type type = Type::IPv4;
Expand Down

0 comments on commit 7c571cd

Please sign in to comment.