Files
thehub/libs/networkmanager/NetworkEndPoint.h

107 lines
3.2 KiB
C++

/*
* This file is part of the Flowee project
* Copyright (C) 2016-2024 Tom Zander <tom@flowee.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef FLOWEE_NETWORKENDPOINT_H
#define FLOWEE_NETWORKENDPOINT_H
#include <string>
#include <cstdint>
#include <Logger.h>
#include <boost/asio/ip/address.hpp>
/// Describes a remote server.
struct EndPoint
{
/// Invalid endpoint
EndPoint()
: peerPort(0),
announcePort(0)
{
}
/**
* Hostname constructor
* Port will be used for both peer and announce port members.
*/
EndPoint(const std::string &hostname, std::uint16_t port)
: hostname(hostname),
peerPort(port),
announcePort(port)
{
}
/**
* IP address constructor.
* Port will be used for both peer and announce port members.
*/
EndPoint(const boost::asio::ip::address &ip, std::uint16_t port)
: ipAddress(ip),
peerPort(port),
announcePort(port)
{
}
bool isValid() const { return announcePort > 0 && (!hostname.empty() || !ipAddress.is_unspecified()); }
std::string toString() const;
/// Implement the P2P format 'addr' of a 16-byte vector encoding the address
static EndPoint fromAddr(const std::vector<char> &addr, int16_t port);
bool operator==(const EndPoint &other) const;
bool operator!=(const EndPoint &other) const {
return !operator==(other);
}
/// write address to a bytearray of 16 bytes.
void toAddr(char *addr) const;
/**
* Return if this is an outgoing connection.
* In networking an incoming socket will have two ports registered,
* the one we connected to (remote announce port) and the local port that we get assigned
* by the OS upon opening the socket.
*/
bool isOutgoing() const {
return announcePort == peerPort;
}
/// @see isOutgoing()
bool isIncoming() const {
return !isOutgoing();
}
boost::asio::ip::address ipAddress;
std::string hostname;
std::uint16_t peerPort = 0;
std::uint16_t announcePort = 0;
/// The connection id refers to the NetworkConnection id, as used by the NetworkManager
int connectionId = -1;
bool encrypted = false;
};
inline Log::Item operator<<(Log::Item item, const EndPoint &ep) {
if (item.isEnabled()) {
const bool old = item.useSpace();
item.nospace() << "EndPoint(" << ep.toString() << ')';
if (old)
return item.space();
}
return item;
}
inline Log::SilentItem operator<<(Log::SilentItem item, const EndPoint&) { return item; }
#endif