Archived
1
0
This repository has been archived on 2023-08-12. You can view files and clone it, but cannot push or open issues or pull requests.
nntpchan/contrib/backends/nntpchan-daemon/libnntpchan/net.cpp

47 lines
1.0 KiB
C++
Raw Normal View History

2017-10-17 19:29:56 +05:00
#include <cstring>
2017-10-11 18:48:27 +05:00
#include <nntpchan/net.hpp>
2016-10-15 18:12:01 +05:00
#include <sstream>
#include <stdexcept>
2017-10-17 19:29:56 +05:00
#include <uv.h>
2016-10-15 18:12:01 +05:00
namespace nntpchan
{
2017-10-17 19:29:56 +05:00
std::string NetAddr::to_string()
{
std::string str("invalid");
const size_t s = 128;
char *buff = new char[s];
2018-05-03 20:47:20 +05:00
if (inet_ntop(AF_INET6, &addr, buff, sizeof(sockaddr_in6)))
2016-10-15 18:12:01 +05:00
{
2017-10-17 19:29:56 +05:00
str = std::string(buff);
delete[] buff;
2016-10-15 18:12:01 +05:00
}
2017-10-17 19:29:56 +05:00
std::stringstream ss;
ss << "[" << str << "]:" << ntohs(addr.sin6_port);
return ss.str();
}
NetAddr::NetAddr() { std::memset(&addr, 0, sizeof(addr)); }
2016-10-15 18:12:01 +05:00
2017-10-17 19:29:56 +05:00
NetAddr ParseAddr(const std::string &addr)
{
NetAddr saddr;
auto n = addr.rfind("]:");
if (n == std::string::npos)
2016-10-15 18:12:01 +05:00
{
2017-10-17 19:29:56 +05:00
throw std::runtime_error("invalid address: " + addr);
2016-10-15 18:12:01 +05:00
}
2017-10-17 19:29:56 +05:00
if (addr[0] != '[')
2016-10-15 18:12:01 +05:00
{
2017-10-17 19:29:56 +05:00
throw std::runtime_error("invalid address: " + addr);
2016-10-15 18:12:01 +05:00
}
2017-10-17 19:29:56 +05:00
auto p = addr.substr(n + 2);
int port = std::atoi(p.c_str());
auto a = addr.substr(0, n);
2018-05-03 20:47:20 +05:00
saddr.addr.sin6_port = htons(port);
saddr.addr.sin6_family = AF_INET6;
inet_pton(AF_INET6, a.c_str(), &saddr.addr);
2017-10-17 19:29:56 +05:00
return saddr;
}
2016-10-15 18:12:01 +05:00
}