Skip to content

Commit

Permalink
libraries: libcore[socektaddress]
Browse files Browse the repository at this point in the history
  • Loading branch information
krishpranav committed Oct 1, 2023
1 parent 5a01bf6 commit be82d03
Showing 1 changed file with 59 additions and 27 deletions.
86 changes: 59 additions & 27 deletions libraries/libcore/socketaddress.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,29 @@
#include <sys/socket.h>
#include <sys/un.h>

namespace Core
namespace Core
{

class SocketAddress
{
class SocketAddress {
public:
enum class Type
{
enum class Type {
Invalid,
IPv4,
Local
}; // enum class Type

SocketAddress() {}
};

SocketAddress() { }
SocketAddress(const IPv4Address& address)
: m_type(Type::IPv4)
, m_ipv4_address(address)
{}
{
}

SocketAddress(const IPv4Address& address, u16 port)
: m_type(Type::IPv4)
, m_ipv4_address(address)
, m_port(port)
{
}

static SocketAddress local(const String& address)
{
Expand All @@ -46,22 +50,37 @@ namespace Core
return addr;
}

Type type() const
{
return m_type;
/**
* @return Type
*/
Type type() const
{
return m_type;
}

bool is_valid() const
{
return m_type != Type::Invalid;
/**
* @return true
* @return false
*/
bool is_valid() const
{
return m_type != Type::Invalid;
}

/**
* @return IPv4Address
*/
IPv4Address ipv4_address() const
{
return m_ipv4_address;
IPv4Address ipv4_address() const
{
return m_ipv4_address;
}

/**
* @return u16
*/
u16 port() const
{
return m_port;
}

/**
Expand All @@ -71,26 +90,35 @@ namespace Core
{
switch (m_type) {
case Type::IPv4:
return String::format("%s:%d", m_ipv4_address.to_string().characters());
return String::format("%s:%d", m_ipv4_address.to_string().characters(), m_port);
case Type::Local:
return m_local_address;
default:
return "[SocketAddress]";
}
}
}

/**
* @return Optional<sockaddr_un>
*/
Optional<sockaddr_un> to_sockaddr_un() const
{
ASSERT(type() == Type::Local);
sockaddr_un address;
address.sun_family = AF_LOCAL;
bool fits = m_local_address.copy_characters_to_buffer(address.sun_family);
bool fits = m_local_address.copy_characters_to_buffer(address.sun_path, sizeof(address.sun_path));
if (!fits)
return {};

return address;
}

/**
* @return sockaddr_in
*/
sockaddr_in to_sockaddr_in() const
{
ASSERT(type() == Type::IPv4);
sockaddr_in address {};
address.sin_family = AF_INET;
address.sin_addr.s_addr = m_ipv4_address.to_in_addr_t();
address.sin_port = htons(m_port);
return address;
}

Expand All @@ -100,5 +128,9 @@ namespace Core
u16 m_port { 0 };
String m_local_address;
}; // class SocketAddress


/**
* @return const LogStream&
*/
const LogStream& operator<<(const LogStream&, const SocketAddress&);
} // namespace Core

0 comments on commit be82d03

Please sign in to comment.