Commit 63bc41bd authored by aligungr's avatar aligungr

getPort() and getAddress() added to network utils

parent ed544330
......@@ -89,6 +89,21 @@ InetAddress::InetAddress(const OctetString &address, uint16_t port) : InetAddres
{
}
uint16_t InetAddress::getPort() const
{
if (storage.ss_family == AF_INET)
{
auto &sin = reinterpret_cast<const sockaddr_in &>(storage);
return static_cast<uint16_t>(sin.sin_port);
}
else if (storage.ss_family == AF_INET6)
{
auto &sin6 = reinterpret_cast<const sockaddr_in6 &>(storage);
return static_cast<uint16_t>(sin6.sin6_port);
}
return 0;
}
Socket::Socket(int domain, int type, int protocol)
{
int sd = socket(domain, type, protocol);
......@@ -263,3 +278,14 @@ void Socket::setReuseAddress() const
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&reuse, sizeof(reuse)) < 0)
throw LibError("setsockopt SO_REUSEADDR failed: ", errno);
}
InetAddress Socket::getAddress() const
{
struct sockaddr_storage storage = {};
socklen_t len = sizeof(storage);
if (getsockname(fd, reinterpret_cast<struct sockaddr *>(&storage), &len) != 0)
throw LibError("getsockname failed: ", errno);
return InetAddress(storage, len);
}
......@@ -26,15 +26,17 @@ struct InetAddress
InetAddress(const sockaddr_storage &storage, socklen_t len);
InetAddress(const std::string &address, uint16_t port);
inline const sockaddr *getSockAddr() const
[[nodiscard]] inline const sockaddr *getSockAddr() const
{
return reinterpret_cast<const sockaddr *>(&storage);
}
inline socklen_t getSockLen() const
[[nodiscard]] inline socklen_t getSockLen() const
{
return len;
}
[[nodiscard]] uint16_t getPort() const;
};
class Socket
......@@ -52,6 +54,7 @@ class Socket
void send(const InetAddress &address, const uint8_t *buffer, size_t size) const;
void close();
[[nodiscard]] bool hasFd() const;
[[nodiscard]] InetAddress getAddress() const;
/* Socket options */
void setReuseAddress() const;
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment