> For the complete documentation index, see [llms.txt](https://docs.edgegap.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.edgegap.com/learn/orchestration/ping-beacons.md).

# Ping Beacons

Use Edgegap ping beacons to measure real player latency and avoid matching players across distant regions.

Ping beacons are a fully managed service providing tiny high-uptime servers placed in major networking hubs worldwide. Game clients ping them to measure their real latency to each region before matchmaking, so players aren't matched across distant regions and get the best possible connection.

## 🟢 Connection Quality

Each player's connection quality is different and changes over time. It depends on:

* wifi signal strength (wireless and mobile connections),
* Internet Service Provider (ISP) conditions,
* local network conditions,
* the networking protocol used,
* Virtual Private Networks (VPNs),
* country-specific restrictions.

Measuring real packet round-trip time to ping beacons captures all of these factors at once, which makes it the most accurate latency metric at any given moment. Game clients use these measurements to **find the best possible match.**

**High beacon ping doesn't always mean high server ping**: there are far more server locations than beacons, and the number of beacons is balanced in real time for the best coverage, the least data transfer, and the fastest measurement.

{% hint style="success" %}
Besides Edgegap's own monitoring, we recommend **tracking connection quality in your own client-side analytics** to understand your player demographics and to discover, triage, and resolve issues quickly.
{% endhint %}

## 🗼 Listing Beacons

Get the current list of beacons from:

* the Matchmaker [In-Depth Look](https://docs.edgegap.com/learn/matchmaking/matchmaker-in-depth.md#matchmaking-api), called from your game client or backend,
* the Edgegap API [endpoint /locations/beacons](https://docs.edgegap.com/api/#tag/Locations/operation/location-beacon-list), called from your backend.

Each beacon has a `host` IP address to ping over ICMP, plus a `udp_port` and a `tcp_port` to ping over UDP and TCP:

{% code title="example-beacon.json" collapsedlinecount="10" %}

```json
{
  "fqdn": "b-c1817d0aae48.pr.edgegap.net",
  "host": "172.234.120.225",
  "location": {
    "administrative_division": "Stockholm County",
    "city": "Stockholm",
    "continent": "Europe",
    "country": "Sweden",
    "latitude": 59.6602,
    "longitude": 17.8301,
    "timezone": "Central European Time"
  },
  "tcp_port": 32760,
  "udp_port": 30903
}
```

{% endcode %}

{% hint style="danger" %}
Beacons are automatically rescaled in real time - adding/removing/replacing existing beacons. Your clients and backend should account for this and **reload list of beacons before each matchmaking round**.
{% endhint %}

{% hint style="info" %}
**Too Many Requests 429** - to keep the platform stable, listing beacons is **rate limited to 40 req/s per organization**. Use an [#active-cache](#active-cache "mention") to stay below the limit.
{% endhint %}

## 🌡️ Measuring Ping

In game development, "ping" and "latency" usually both mean [packet Round-Trip Time](https://www.cloudflare.com/learning/cdn/glossary/round-trip-time-rtt/) (RTT): the time a packet takes to reach a server and come back.

{% hint style="success" %}
Pinging beacons over **ICMP, UDP, or TCP is not rate limited**.
{% endhint %}

### Automatic

<figure><img src="https://framerusercontent.com/images/A3i6fAuTXRu1BNFPDKkOZ3Spk.png" alt="Latency measurement flow between game clients, ping beacons, and the Matchmaker"><figcaption></figcaption></figure>

Our SDKs measure beacon ping for you and send results to the matchmaker, see :

* Unity [Developer Tools](https://docs.edgegap.com/unity/developer-tools.md#software-development-kit):
  * [install package using Unity Package Manager for free](https://github.com/edgegap/sdk-unity-sessions-matchmaker-server-browser),
  * [explore our getting started guide and complete examples](https://docs.edgegap.com/unity/matchmaking.md).
* Unreal Engine [Developer Tools](https://docs.edgegap.com/unreal-engine/developer-tools.md#integration-kit):
  * [read the documentation](https://egik.betide.studio/) by Betide Studios,
  * [install from Fab Marketplace](https://www.fab.com/listings/ff17ad88-12a1-49cf-9a41-31695ed11e16) (free for Personal use).

### Manual

To measure ping yourself, for example in a custom engine, a backend, or a diagnostics tool, ping each beacon using any protocol it supports, in this order:

* **ICMP** - standard `ping` to the beacon `host`,
  * **try it first - the most reliable and compatible with all devices (incl. mobile).**
* **UDP** - send a small datagram to `udp_port` and time the echoed reply,
  * the closest match to real-time game traffic.
* **TCP** - time the TCP handshake (connect) to `tcp_port`,
  * works on most restrictive networks.

Each example below sends several samples to a single beacon and prints the minimum, median, and maximum round-trip time:

{% tabs %}
{% tab title="C#" %}
{% code title="IcmpPing.cs" lineNumbers="true" expandable="true" collapsedlinecount="10" %}

```csharp
// ICMP ping to an Edgegap ping beacon.
// Usage: IcmpPing <beacon_host> [samples]
// Requires .NET Standard 2.1+ (.NET 6+, Unity 2021+). On Android, iOS and WebGL use UnityEngine.Ping instead.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Threading.Tasks;

public static class IcmpPing
{
    // Returns the round-trip time in milliseconds, or null if the beacon did not reply in time.
    public static async Task<double?> PingAsync(string host, int timeoutMs = 1000)
    {
        using var ping = new Ping();
        try
        {
            PingReply reply = await ping.SendPingAsync(host, timeoutMs);
            return reply.Status == IPStatus.Success ? reply.RoundtripTime : (double?)null;
        }
        catch (PingException)
        {
            return null; // host unreachable or ICMP blocked by the network
        }
    }

    public static async Task Main(string[] args)
    {
        if (args.Length < 1)
        {
            Console.WriteLine("usage: IcmpPing <beacon_host> [samples]");
            return;
        }
        string host = args[0];
        int samples = args.Length > 1 ? int.Parse(args[1]) : 5;

        var results = new List<double>();
        for (int i = 0; i < samples; i++)
        {
            double? rtt = await PingAsync(host);
            Console.WriteLine(rtt.HasValue ? $"reply from {host} time={rtt:F1} ms" : "request timed out");
            if (rtt.HasValue) results.Add(rtt.Value);
            await Task.Delay(200);
        }

        if (results.Count == 0)
        {
            Console.WriteLine("beacon unreachable over ICMP, try UDP or TCP");
            return;
        }
        results.Sort();
        Console.WriteLine($"min={results.First():F1} ms median={results[results.Count / 2]:F1} ms " +
                          $"max={results.Last():F1} ms loss={100 * (samples - results.Count) / samples}%");
    }
}
```

{% endcode %}

{% code title="UdpPing.cs" lineNumbers="true" expandable="true" collapsedlinecount="10" %}

```csharp
// UDP ping to an Edgegap ping beacon: send a datagram to the beacon's udp_port and time the reply.
// Usage: UdpPing <beacon_host> <udp_port> [samples]
// Requires .NET Standard 2.1+ (.NET 6+, Unity 2021+).
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

public static class UdpPing
{
    // Returns the round-trip time in milliseconds, or null if no reply arrived in time.
    public static Task<double?> PingAsync(IPAddress address, int port, int timeoutMs = 1000) =>
        Task.Run(() =>
        {
            using var socket = new Socket(address.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
            socket.ReceiveTimeout = timeoutMs;
            socket.Connect(address, port); // only accept datagrams coming back from the beacon

            byte[] payload = Encoding.ASCII.GetBytes("ping");
            byte[] buffer = new byte[1500];

            var stopwatch = Stopwatch.StartNew();
            socket.Send(payload);
            try
            {
                socket.Receive(buffer);
            }
            catch (SocketException)
            {
                return (double?)null; // timed out, or the port is unreachable
            }
            return stopwatch.Elapsed.TotalMilliseconds;
        });

    public static async Task Main(string[] args)
    {
        if (args.Length < 2)
        {
            Console.WriteLine("usage: UdpPing <beacon_host> <udp_port> [samples]");
            return;
        }
        // Resolve once, so DNS lookup time is not counted as latency.
        IPAddress address = (await Dns.GetHostAddressesAsync(args[0]))
            .First(a => a.AddressFamily == AddressFamily.InterNetwork);
        int port = int.Parse(args[1]);
        int samples = args.Length > 2 ? int.Parse(args[2]) : 5;

        var results = new List<double>();
        for (int i = 0; i < samples; i++)
        {
            double? rtt = await PingAsync(address, port);
            Console.WriteLine(rtt.HasValue ? $"reply from {address}:{port} time={rtt:F1} ms" : "request timed out");
            if (rtt.HasValue) results.Add(rtt.Value);
            await Task.Delay(200);
        }

        if (results.Count == 0)
        {
            Console.WriteLine("beacon unreachable over UDP, try TCP");
            return;
        }
        results.Sort();
        Console.WriteLine($"min={results.First():F1} ms median={results[results.Count / 2]:F1} ms " +
                          $"max={results.Last():F1} ms loss={100 * (samples - results.Count) / samples}%");
    }
}
```

{% endcode %}

{% code title="TcpPing.cs" lineNumbers="true" expandable="true" collapsedlinecount="10" %}

```csharp
// TCP ping to an Edgegap ping beacon: time the TCP handshake (connect) to the beacon's tcp_port.
// Usage: TcpPing <beacon_host> <tcp_port> [samples]
// Requires .NET Standard 2.1+ (.NET 6+, Unity 2021+).
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;

public static class TcpPing
{
    // Returns the handshake time in milliseconds, or null if the connection failed or timed out.
    public static async Task<double?> PingAsync(IPAddress address, int port, int timeoutMs = 1000)
    {
        using var socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };

        var stopwatch = Stopwatch.StartNew();
        Task connect = socket.ConnectAsync(address, port);
        if (await Task.WhenAny(connect, Task.Delay(timeoutMs)) != connect)
        {
            // Timed out: disposing the socket aborts the pending connect, observe its exception.
            _ = connect.ContinueWith(t => t.Exception, TaskContinuationOptions.OnlyOnFaulted);
            return null;
        }
        try
        {
            await connect;
        }
        catch (SocketException)
        {
            return null; // connection refused or unreachable
        }
        return stopwatch.Elapsed.TotalMilliseconds; // SYN -> SYN/ACK is one round trip
    }

    public static async Task Main(string[] args)
    {
        if (args.Length < 2)
        {
            Console.WriteLine("usage: TcpPing <beacon_host> <tcp_port> [samples]");
            return;
        }
        // Resolve once, so DNS lookup time is not counted as latency.
        IPAddress address = (await Dns.GetHostAddressesAsync(args[0]))
            .First(a => a.AddressFamily == AddressFamily.InterNetwork);
        int port = int.Parse(args[1]);
        int samples = args.Length > 2 ? int.Parse(args[2]) : 5;

        var results = new List<double>();
        for (int i = 0; i < samples; i++)
        {
            double? rtt = await PingAsync(address, port);
            Console.WriteLine(rtt.HasValue ? $"connected to {address}:{port} time={rtt:F1} ms" : "connection failed");
            if (rtt.HasValue) results.Add(rtt.Value);
            await Task.Delay(200);
        }

        if (results.Count == 0)
        {
            Console.WriteLine("beacon unreachable over TCP");
            return;
        }
        results.Sort();
        Console.WriteLine($"min={results.First():F1} ms median={results[results.Count / 2]:F1} ms " +
                          $"max={results.Last():F1} ms loss={100 * (samples - results.Count) / samples}%");
    }
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code title="icmp\_ping.cpp" lineNumbers="true" expandable="true" collapsedlinecount="10" %}

```cpp
// ICMP ping to an Edgegap ping beacon.
// Build (Windows): cl /EHsc /std:c++17 icmp_ping.cpp ws2_32.lib iphlpapi.lib
// Build (Linux/macOS): g++ -std=c++17 icmp_ping.cpp -o icmp_ping
// Usage: icmp_ping <beacon_host> [samples]
// Linux uses unprivileged ICMP sockets, allowed when your group is in net.ipv4.ping_group_range
// (default on most desktop distros), otherwise run with CAP_NET_RAW or use UDP/TCP instead.
#include <algorithm>
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <optional>
#include <string>
#include <thread>
#include <vector>

#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <icmpapi.h>
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "iphlpapi.lib")
#else
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <unistd.h>
#endif

using Clock = std::chrono::steady_clock;

// Resolve once, so DNS lookup time is not counted as latency.
static bool resolve(const char* host, sockaddr_in& out) {
    addrinfo hints{}, *result = nullptr;
    hints.ai_family = AF_INET;
    if (getaddrinfo(host, nullptr, &hints, &result) != 0 || !result) return false;
    out = *reinterpret_cast<sockaddr_in*>(result->ai_addr);
    freeaddrinfo(result);
    return true;
}

#ifdef _WIN32
// Windows: the ICMP helper API sends an echo request without admin rights.
static std::optional<double> icmp_ping(const sockaddr_in& addr, int /*seq*/, int timeout_ms = 1000) {
    HANDLE icmp = IcmpCreateFile();
    if (icmp == INVALID_HANDLE_VALUE) return std::nullopt;

    char payload[32] = "edgegap-ping-beacon";
    char reply[sizeof(ICMP_ECHO_REPLY) + sizeof(payload) + 8];
    DWORD count = IcmpSendEcho(icmp, addr.sin_addr.s_addr, payload, sizeof(payload), nullptr, reply,
                               sizeof(reply), timeout_ms);
    IcmpCloseHandle(icmp);

    auto* echo = reinterpret_cast<ICMP_ECHO_REPLY*>(reply);
    if (count == 0 || echo->Status != IP_SUCCESS) return std::nullopt;
    return static_cast<double>(echo->RoundTripTime);
}
#else
struct IcmpEcho {
    uint8_t type, code;
    uint16_t checksum, id, seq;
    char payload[32];
};

static uint16_t checksum(const void* data, size_t len) {
    auto* words = static_cast<const uint16_t*>(data);
    uint32_t sum = 0;
    for (; len > 1; len -= 2) sum += *words++;
    if (len == 1) sum += *reinterpret_cast<const uint8_t*>(words);
    sum = (sum >> 16) + (sum & 0xFFFF);
    sum += sum >> 16;
    return static_cast<uint16_t>(~sum);
}

// Linux/macOS: unprivileged ICMP datagram socket (no root needed).
static std::optional<double> icmp_ping(const sockaddr_in& addr, int seq, int timeout_ms = 1000) {
    int s = socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP);
    if (s < 0) return std::nullopt; // ICMP sockets not permitted for this user

    IcmpEcho request{};
    request.type = 8; // echo request
    request.id = htons(static_cast<uint16_t>(getpid() & 0xFFFF)); // Linux replaces it with the socket id
    request.seq = htons(static_cast<uint16_t>(seq));
    std::strncpy(request.payload, "edgegap-ping-beacon", sizeof(request.payload) - 1);
    request.checksum = checksum(&request, sizeof(request));

    auto start = Clock::now();
    auto deadline = start + std::chrono::milliseconds(timeout_ms);
    sendto(s, &request, sizeof(request), 0, reinterpret_cast<const sockaddr*>(&addr), sizeof(addr));

    while (Clock::now() < deadline) {
        auto left = std::chrono::duration_cast<std::chrono::microseconds>(deadline - Clock::now()).count();
        timeval tv{static_cast<long>(left / 1000000), static_cast<long>(left % 1000000)};
        fd_set readable;
        FD_ZERO(&readable);
        FD_SET(s, &readable);
        if (select(s + 1, &readable, nullptr, nullptr, &tv) <= 0) break; // timed out

        uint8_t buffer[1500];
        ssize_t n = recv(s, buffer, sizeof(buffer), 0);
        if (n <= 0) break;

        // macOS includes the IP header in the reply, Linux does not.
        size_t offset = (buffer[0] >> 4) == 4 ? (buffer[0] & 0x0F) * 4 : 0;
        if (static_cast<size_t>(n) < offset + 8) continue;
        auto* reply = reinterpret_cast<IcmpEcho*>(buffer + offset);
        if (reply->type == 0 && ntohs(reply->seq) == seq) { // echo reply for our request
            double rtt = std::chrono::duration<double, std::milli>(Clock::now() - start).count();
            close(s);
            return rtt;
        }
    }
    close(s);
    return std::nullopt;
}
#endif

int main(int argc, char** argv) {
    if (argc < 2) {
        std::printf("usage: icmp_ping <beacon_host> [samples]\n");
        return 1;
    }
#ifdef _WIN32
    WSADATA wsa;
    WSAStartup(MAKEWORD(2, 2), &wsa);
#endif
    sockaddr_in addr{};
    if (!resolve(argv[1], addr)) {
        std::printf("could not resolve %s\n", argv[1]);
        return 1;
    }
    int samples = argc > 2 ? std::stoi(argv[2]) : 5;

    std::vector<double> results;
    for (int i = 0; i < samples; i++) {
        auto rtt = icmp_ping(addr, i + 1);
        if (rtt) {
            std::printf("reply from %s time=%.1f ms\n", argv[1], *rtt);
            results.push_back(*rtt);
        } else {
            std::printf("request timed out\n");
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(200));
    }

    if (results.empty()) {
        std::printf("beacon unreachable over ICMP, try UDP or TCP\n");
    } else {
        std::sort(results.begin(), results.end());
        std::printf("min=%.1f ms median=%.1f ms max=%.1f ms loss=%d%%\n", results.front(),
                    results[results.size() / 2], results.back(),
                    100 * (samples - static_cast<int>(results.size())) / samples);
    }
#ifdef _WIN32
    WSACleanup();
#endif
    return 0;
}
```

{% endcode %}

{% code title="udp\_ping.cpp" lineNumbers="true" expandable="true" collapsedlinecount="10" %}

```cpp
// UDP ping to an Edgegap ping beacon: send a datagram to the beacon's udp_port and time the reply.
// Build (Windows): cl /EHsc /std:c++17 udp_ping.cpp ws2_32.lib
// Build (Linux/macOS): g++ -std=c++17 udp_ping.cpp -o udp_ping
// Usage: udp_ping <beacon_host> <udp_port> [samples]
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <optional>
#include <string>
#include <thread>
#include <vector>

#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
using socket_t = SOCKET;
#define CLOSE_SOCKET closesocket
#else
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <unistd.h>
using socket_t = int;
#define INVALID_SOCKET (-1)
#define CLOSE_SOCKET close
#endif

using Clock = std::chrono::steady_clock;

// Resolve once, so DNS lookup time is not counted as latency.
static bool resolve(const char* host, const char* port, sockaddr_in& out) {
    addrinfo hints{}, *result = nullptr;
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_DGRAM;
    if (getaddrinfo(host, port, &hints, &result) != 0 || !result) return false;
    out = *reinterpret_cast<sockaddr_in*>(result->ai_addr);
    freeaddrinfo(result);
    return true;
}

// Returns the round-trip time in milliseconds, or nothing if no reply arrived in time.
static std::optional<double> udp_ping(const sockaddr_in& addr, int timeout_ms = 1000) {
    socket_t s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (s == INVALID_SOCKET) return std::nullopt;

#ifdef _WIN32
    DWORD timeout = timeout_ms;
#else
    timeval timeout{timeout_ms / 1000, (timeout_ms % 1000) * 1000};
#endif
    setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char*>(&timeout), sizeof(timeout));
    // Connected UDP socket: only accept datagrams coming back from the beacon.
    connect(s, reinterpret_cast<const sockaddr*>(&addr), sizeof(addr));

    const char payload[] = "ping";
    char buffer[1500];

    auto start = Clock::now();
    send(s, payload, sizeof(payload) - 1, 0);
    int received = recv(s, buffer, sizeof(buffer), 0);
    double rtt = std::chrono::duration<double, std::milli>(Clock::now() - start).count();
    CLOSE_SOCKET(s);

    if (received < 0) return std::nullopt; // timed out, or the port is unreachable
    return rtt;
}

int main(int argc, char** argv) {
    if (argc < 3) {
        std::printf("usage: udp_ping <beacon_host> <udp_port> [samples]\n");
        return 1;
    }
#ifdef _WIN32
    WSADATA wsa;
    WSAStartup(MAKEWORD(2, 2), &wsa);
#endif
    sockaddr_in addr{};
    if (!resolve(argv[1], argv[2], addr)) {
        std::printf("could not resolve %s\n", argv[1]);
        return 1;
    }
    int samples = argc > 3 ? std::stoi(argv[3]) : 5;

    std::vector<double> results;
    for (int i = 0; i < samples; i++) {
        auto rtt = udp_ping(addr);
        if (rtt) {
            std::printf("reply from %s:%s time=%.1f ms\n", argv[1], argv[2], *rtt);
            results.push_back(*rtt);
        } else {
            std::printf("request timed out\n");
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(200));
    }

    if (results.empty()) {
        std::printf("beacon unreachable over UDP, try TCP\n");
    } else {
        std::sort(results.begin(), results.end());
        std::printf("min=%.1f ms median=%.1f ms max=%.1f ms loss=%d%%\n", results.front(),
                    results[results.size() / 2], results.back(),
                    100 * (samples - static_cast<int>(results.size())) / samples);
    }
#ifdef _WIN32
    WSACleanup();
#endif
    return 0;
}
```

{% endcode %}

{% code title="tcp\_ping.cpp" lineNumbers="true" expandable="true" collapsedlinecount="10" %}

```cpp
// TCP ping to an Edgegap ping beacon: time the TCP handshake (connect) to the beacon's tcp_port.
// Build (Windows): cl /EHsc /std:c++17 tcp_ping.cpp ws2_32.lib
// Build (Linux/macOS): g++ -std=c++17 tcp_ping.cpp -o tcp_ping
// Usage: tcp_ping <beacon_host> <tcp_port> [samples]
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <optional>
#include <string>
#include <thread>
#include <vector>

#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
using socket_t = SOCKET;
#define CLOSE_SOCKET closesocket
#else
#include <arpa/inet.h>
#include <cerrno>
#include <fcntl.h>
#include <netdb.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <unistd.h>
using socket_t = int;
#define INVALID_SOCKET (-1)
#define CLOSE_SOCKET close
#endif

using Clock = std::chrono::steady_clock;

// Resolve once, so DNS lookup time is not counted as latency.
static bool resolve(const char* host, const char* port, sockaddr_in& out) {
    addrinfo hints{}, *result = nullptr;
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    if (getaddrinfo(host, port, &hints, &result) != 0 || !result) return false;
    out = *reinterpret_cast<sockaddr_in*>(result->ai_addr);
    freeaddrinfo(result);
    return true;
}

// Returns the handshake time in milliseconds, or nothing if the connection failed or timed out.
static std::optional<double> tcp_ping(const sockaddr_in& addr, int timeout_ms = 1000) {
    socket_t s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (s == INVALID_SOCKET) return std::nullopt;

    // Non-blocking connect, so we can enforce our own timeout.
#ifdef _WIN32
    u_long non_blocking = 1;
    ioctlsocket(s, FIONBIO, &non_blocking);
#else
    fcntl(s, F_SETFL, fcntl(s, F_GETFL, 0) | O_NONBLOCK);
#endif

    auto start = Clock::now();
    int rc = connect(s, reinterpret_cast<const sockaddr*>(&addr), sizeof(addr));
#ifdef _WIN32
    bool pending = rc != 0 && WSAGetLastError() == WSAEWOULDBLOCK;
#else
    bool pending = rc != 0 && errno == EINPROGRESS;
#endif
    if (rc != 0 && !pending) {
        CLOSE_SOCKET(s);
        return std::nullopt;
    }

    if (pending) {
        fd_set writable, failed;
        FD_ZERO(&writable);
        FD_ZERO(&failed);
        FD_SET(s, &writable);
        FD_SET(s, &failed);
        timeval tv{timeout_ms / 1000, (timeout_ms % 1000) * 1000};
        if (select(static_cast<int>(s) + 1, nullptr, &writable, &failed, &tv) <= 0) {
            CLOSE_SOCKET(s); // timed out
            return std::nullopt;
        }
        int error = 0;
        socklen_t len = sizeof(error);
        getsockopt(s, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&error), &len);
        if (error != 0) {
            CLOSE_SOCKET(s); // connection refused or unreachable
            return std::nullopt;
        }
    }

    double rtt = std::chrono::duration<double, std::milli>(Clock::now() - start).count();
    CLOSE_SOCKET(s);
    return rtt; // SYN -> SYN/ACK is one round trip
}

int main(int argc, char** argv) {
    if (argc < 3) {
        std::printf("usage: tcp_ping <beacon_host> <tcp_port> [samples]\n");
        return 1;
    }
#ifdef _WIN32
    WSADATA wsa;
    WSAStartup(MAKEWORD(2, 2), &wsa);
#endif
    sockaddr_in addr{};
    if (!resolve(argv[1], argv[2], addr)) {
        std::printf("could not resolve %s\n", argv[1]);
        return 1;
    }
    int samples = argc > 3 ? std::stoi(argv[3]) : 5;

    std::vector<double> results;
    for (int i = 0; i < samples; i++) {
        auto rtt = tcp_ping(addr);
        if (rtt) {
            std::printf("connected to %s:%s time=%.1f ms\n", argv[1], argv[2], *rtt);
            results.push_back(*rtt);
        } else {
            std::printf("connection failed\n");
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(200));
    }

    if (results.empty()) {
        std::printf("beacon unreachable over TCP\n");
    } else {
        std::sort(results.begin(), results.end());
        std::printf("min=%.1f ms median=%.1f ms max=%.1f ms loss=%d%%\n", results.front(),
                    results[results.size() / 2], results.back(),
                    100 * (samples - static_cast<int>(results.size())) / samples);
    }
#ifdef _WIN32
    WSACleanup();
#endif
    return 0;
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

{% hint style="info" %}
**Ping each beacon several (3-5) times and report the average** to smooth out spikes, and resolve hostnames before you start timing so DNS lookups aren't counted as latency.
{% endhint %}

Send the results to the matchmaker as a map of beacon city to average latency in milliseconds, see [In-Depth Look](https://docs.edgegap.com/learn/matchmaking/matchmaker-in-depth.md#ping-optimization).

## 🎮 Player Selection

Beacon measurements can also power in-game location choices.

{% hint style="success" %}
After updates, test your game under poor network conditions to find playability limits.
{% endhint %}

### Region or Hub UI

Some players prefer to enable or disable matchmaking regions from a list of locations.

**Automatically disable high latency hubs:**

* list all available beacons,
* [measure round-trip time](#measuring-round-trip-time) to every beacon,
* **disable a hub if its latency exceeds playable threshold,**
* label enabled hubs in your game UI with the beacon's `city`.

{% hint style="warning" %}
Call these locations "Hubs", or another **name that doesn't suggest they are the only server locations**. Edgegap orchestrates game servers across 615+ physical locations and 17+ data center providers to deploy each match in the ideal location.
{% endhint %}

### High Ping Players

{% hint style="info" %}
To let players override [Deployments](https://docs.edgegap.com/learn/orchestration/deployments.md#server-placement) provide beacon IP when [matchmaking](https://docs.edgegap.com/learn/matchmaking/matchmaker-in-depth.md#endpoint-tickets) or [deploying](https://docs.edgegap.com/docs/api/dedicated-servers.md#deployments). For best player experience, warn players this may result in increased latency due to remotely located server.
{% endhint %}

Some players with high ping to all beacons due to ISP[^1] issues or slow connection (e.g. wireless/mobile) may cause lags and degrade game experience for others. To mitigate this issue:

* Gradually expand allowed latency maximum and difference (see [Advanced Example Config](https://docs.edgegap.com/learn/matchmaking.md#advanced-example)),
  * players with high ping may have to wait longer than usual to find a match.
* Alternatively, allow players to override measurement with manual region selection, only sending fake ping values for the player-selected regions only (e.g. 25ms for fast match),
  * this may negatively impact player experience of the players' teammates and opponents.

{% hint style="info" %}
**High beacon ping doesn’t always result in high server ping**. Deployments are available in more locations than beacons. Beacons are orchestrated in real time to prioritize global coverage and reliability.
{% endhint %}

{% hint style="success" %}
See [Matchmaking](https://docs.edgegap.com/learn/matchmaking.md) for **automated ping measurement using our SDKs**.
{% endhint %}

## 🧠 Active Cache

**If you don't use the** [**Matchmaker**](https://docs.edgegap.com/learn/matchmaking.md) (e.g. custom backend), add extra scalability insurance before a large release: **run your own backend service that caches the beacon list in memory** and serves it to game clients, instead of calling Edgegap API from clients.

This service should **refresh the beacon list with a single API request every 60 seconds.**

[^1]: Internet Service Provider
