27 if (this->
hostname.empty() && this->address.ss_family != AF_UNSPEC) {
30 getnameinfo((
struct sockaddr *)&this->
address, this->
address_length, buffer,
sizeof(buffer),
nullptr, 0, NI_NUMERICHOST);
42 switch (this->
address.ss_family) {
45 return ntohs(((
const struct sockaddr_in *)&this->
address)->sin_port);
48 return ntohs(((
const struct sockaddr_in6 *)&this->address)->sin6_port);
61 switch (this->
address.ss_family) {
64 ((
struct sockaddr_in*)&this->
address)->sin_port = htons(port);
68 ((
struct sockaddr_in6*)&this->
address)->sin6_port = htons(port);
85 case AF_INET:
return with_family ?
"{}:{} (IPv4)" :
"{}:{}";
86 case AF_INET6:
return with_family ?
"[{}]:{} (IPv6)" :
"[{}]:{}";
87 default:
return with_family ?
"{}:{} (IPv?)" :
"{}:{}";
108 return !INVALID_SOCKET;
139 return this->
address.ss_family == family;
153 int cidr = this->
address.ss_family == AF_INET ? 32 : 128;
164 if (tmp_cidr > 0 && tmp_cidr < cidr) cidr = tmp_cidr;
169 switch (this->
address.ss_family) {
171 ip = (uint32_t*)&((
struct sockaddr_in*)&this->
address)->sin_addr.s_addr;
172 mask = (uint32_t*)&((
struct sockaddr_in*)&mask_address.
address)->sin_addr.s_addr;
176 ip = (uint32_t*)&((
struct sockaddr_in6*)&this->address)->sin6_addr;
177 mask = (uint32_t*)&((
struct sockaddr_in6*)&mask_address.
address)->sin6_addr;
185 uint32_t msk = cidr >= 32 ? (uint32_t)-1 : htonl(-(1 << (32 - cidr)));
186 if ((*mask++ & msk) != (*ip++ & msk))
return false;
206 struct addrinfo hints{};
207 hints.ai_family = family;
208 hints.ai_flags = flags;
209 hints.ai_socktype = socktype;
212 std::string port_name = fmt::format(
"{}", this->
GetPort());
214 bool reset_hostname =
false;
218 if (this->
hostname.empty() && this->address_length == 0 && this->GetPort() == 0) {
219 reset_hostname =
true;
220 int fam = this->
address.ss_family;
221 if (fam == AF_UNSPEC) fam = family;
222 this->
hostname = fam == AF_INET ?
"0.0.0.0" :
"::";
225 static bool _resolve_timeout_error_message_shown =
false;
226 auto start = std::chrono::steady_clock::now();
227 int e = getaddrinfo(this->
hostname.empty() ?
nullptr : this->hostname.c_str(), port_name.c_str(), &hints, &ai);
228 auto end = std::chrono::steady_clock::now();
229 std::chrono::seconds duration = std::chrono::duration_cast<std::chrono::seconds>(end - start);
230 if (!_resolve_timeout_error_message_shown && duration >= std::chrono::seconds(5)) {
234 _resolve_timeout_error_message_shown =
true;
238 if (reset_hostname) this->
hostname.clear();
245 return INVALID_SOCKET;
248 SOCKET sock = INVALID_SOCKET;
249 for (
struct addrinfo *runp = ai; runp !=
nullptr; runp = runp->ai_next) {
255 if (std::any_of(
sockets->begin(),
sockets->end(), [&
address](
const auto &p) { return p.second == address; }))
continue;
258 if (sock == INVALID_SOCKET)
continue;
262 assert(
sizeof(this->
address) >= runp->ai_addrlen);
263 std::copy_n(
reinterpret_cast<const std::byte *
>(runp->ai_addr), runp->ai_addrlen,
reinterpret_cast<std::byte *
>(&this->address));
271 if (this->
address.ss_family == AF_INET) {
272 sockaddr_in *address_ipv4 = (sockaddr_in *)&this->
address;
273 std::ranges::fill(address_ipv4->sin_zero, 0);
280 (*sockets)[sock] = std::move(addr);
281 sock = INVALID_SOCKET;
297 SOCKET sock = socket(runp->ai_family, runp->ai_socktype, runp->ai_protocol);
298 if (sock == INVALID_SOCKET) {
302 return INVALID_SOCKET;
305 if (runp->ai_socktype == SOCK_STREAM && !
SetNoDelay(sock)) {
314 if (runp->ai_family == AF_INET6 &&
315 setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY,
reinterpret_cast<const char *
>(&on),
sizeof(on)) == -1) {
319 if (bind(sock, runp->ai_addr, (
int)runp->ai_addrlen) != 0) {
322 return INVALID_SOCKET;
325 if (runp->ai_socktype != SOCK_DGRAM && listen(sock, 1) != 0) {
328 return INVALID_SOCKET;
354 this->hostname.empty() && this->GetPort() == 0) {
371 case SOCK_STREAM:
return "tcp";
372 case SOCK_DGRAM:
return "udp";
373 default:
return "unsupported";
386 case AF_UNSPEC:
return "either IPv4 or IPv6";
387 case AF_INET:
return "IPv4";
388 case AF_INET6:
return "IPv6";
389 default:
return "unsupported";
400 sockaddr_storage addr = {};
401 socklen_t addr_len =
sizeof(addr);
402 if (getpeername(sock, (sockaddr *)&addr, &addr_len) != 0) {
416 sockaddr_storage addr = {};
417 socklen_t addr_len =
sizeof(addr);
418 if (getsockname(sock, (sockaddr *)&addr, &addr_len) != 0) {
452 uint16_t port = default_port;
static SOCKET ListenLoopProc(addrinfo *runp)
Helper function to resolve a listening.
static SOCKET ResolveLoopProc(addrinfo *)
Helper function to resolve without opening a socket.
static std::string_view GetAddressFormatString(uint16_t family, bool with_family)
Helper to get the formatting string of an address for a given family.
Wrapper for network addresses.
@ InviteCode
Server-address is based on an invite code.
@ Direct
Server-address is based on an hostname:port.
std::map< SOCKET, NetworkAddress > SocketList
Type for a mapping between address and socket.
Wrapper for (un)resolved network addresses; there's no reason to transform a numeric IP to a string a...
static NetworkAddress GetPeerAddress(SOCKET sock)
Get the peer address of a socket as NetworkAddress.
bool resolved
Whether the address has been (tried to be) resolved.
int GetAddressLength()
Get the (valid) length of the address.
sockaddr_storage address
The resolved address.
static std::string_view AddressFamilyAsString(int family)
Convert the address family into a string.
bool IsFamily(int family)
Checks of this address is of the given family.
bool IsResolved() const
Check whether the IP address has been resolved already.
static const std::string GetPeerName(SOCKET sock)
Get the peer name of a socket in string format.
SOCKET(* LoopProc)(addrinfo *runp)
Helper function to resolve something to a socket.
static std::string_view SocketTypeAsString(int socktype)
Convert the socket type into a string.
static NetworkAddress GetSockAddress(SOCKET sock)
Get the local address of a socket as NetworkAddress.
std::string hostname
The hostname.
uint16_t GetPort() const
Get the port.
void Listen(int socktype, SocketList *sockets)
Make the given socket listen.
SOCKET Resolve(int family, int socktype, int flags, SocketList *sockets, LoopProc func)
Resolve this address into a socket.
void SetPort(uint16_t port)
Set the port.
NetworkAddress(struct sockaddr_storage &address, int address_length)
Create a network address based on a resolved IP and port.
const sockaddr_storage * GetAddress()
Get the address in its internal representation.
const std::string & GetHostname()
Get the hostname; in case it wasn't given the IPv4 dotted representation is given.
int address_length
The length of the resolved address.
std::string GetAddressAsString(bool with_family=true)
Get the address as a string, e.g.
bool IsInNetmask(std::string_view netmask)
Checks whether this IP address is contained by the given netmask.
static NetworkError GetLast()
Get the last network error.
std::string connection_string
The connection string for this ServerAddress.
static ServerAddress Parse(std::string_view connection_string, uint16_t default_port, CompanyID *company_id=nullptr)
Convert a string containing either "hostname", "hostname:port" or invite code to a ServerAddress,...
ServerAddress(ServerAddressType type, std::string &&connection_string)
Create a new ServerAddress object.
Parse data from a string / buffer.
std::string_view ReadUntilChar(char c, SeparatorUsage sep)
Read data until the first occurrence of 8-bit char 'c', and advance reader.
@ SKIP_ONE_SEPARATOR
Read and discard one separator, do not include it in the result.
bool AnyBytesLeft() const noexcept
Check whether any bytes left to read.
T ReadIntegerBase(int base, T def=0, bool clamp=false)
Read and parse an integer in number 'base', and advance the reader.
static const uint NETWORK_HOSTNAME_LENGTH
The maximum length of the host name, in bytes including '\0'.
Functions related to debugging.
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
@ Net
Net message facility.
@ Critical
Critical, user should know about this.
@ Error
Error, but we are recovering.
std::string_view ParseCompanyFromConnectionString(std::string_view connection_string, CompanyID *company_id)
Parse the company part ("#company" postfix) of a connecting string.
std::string_view ParseFullConnectionString(std::string_view connection_string, uint16_t &port, CompanyID *company_id)
Converts a string to ip/port/company Format: IP:port::company.
Network functions used by other parts of OpenTTD.
Variables and function used internally.
bool SetReusePort(SOCKET d)
Try to set the socket to reuse ports.
bool SetNoDelay(SOCKET d)
Try to set the socket to not delay sending.
bool SetNonBlocking(SOCKET d)
Try to set the socket into non-blocking mode.
A number of safeguards to prevent using unsafe methods.
Definition of base types and functions in a cross-platform compatible way.
SocketList TCPListenHandler< Tsocket, EnumPacketType, Tfull_packet, Tban_packet >::sockets
Instantiate the sockets.
std::string FS2OTTD(std::wstring_view name)
Convert to OpenTTD's encoding from a wide string.