Home Guides Host-authoritative networking

Host-authoritative networking in s&box

Updated

Clients ask, the host decides. How to write s&box networking code that a modified client cannot cheat, with C# examples for a shop, an inventory and a weapon.

The rule: clients send intent, the host owns truth

In a host-authoritative s&box game, the host (either a listen-server host or a headless dedicated server) is the single source of truth for every gameplay variable that affects another player. A client never announces "I now have 500 coins", "I moved item X into slot 3", or "I dealt 75 damage to that player". Instead, the client announces its intent—"I want to buy item X" or "I pulled the trigger along this aim ray"—and the host decides whether that transition is legal.

Anything transmitted by a client over UDP can be forged, delayed by packet loss, replayed out of order, or sent at twenty times the normal frame rate by a modified client or macro script. Treat every incoming RPC argument with the exact same suspicion a web backend applies to an unauthenticated HTTP POST body.

Even if a player edits their local memory, the host refuses the change and the next network snapshot overwrites the tampered value.

The pattern: ask, check, apply

Store the authoritative value in a [Sync] property with a private setter so only host-side code can mutate it. Expose one narrowly scoped [Rpc.Host] method per player action. Inside that method, verify that execution is on the host, resolve the caller identity from Rpc.Caller rather than a method parameter, validate all arguments against your server-side catalog, check cooldowns and world distance, and only then mutate the [Sync] property.

The sample below is the whole check for a shop purchase. Attribute and class names follow the s&box component networking model.

public sealed class Wallet : Component
{
    [Sync] public int Coins { get; private set; } = 100;
    private TimeSince _lastPurchaseTime;

    // Called by a client. Runs exclusively on the host.
    [Rpc.Host]
    public void RequestBuy( string itemId )
    {
        if ( !Networking.IsHost ) return;
        var caller = Rpc.Caller;                       // who sent the RPC packet
        if ( caller is null ) return;
        if ( Network.OwnerId != Guid.Empty ? caller.Id != Network.OwnerId : !caller.IsHost ) return;   // the owner, or the host if nobody owns it
        if ( _lastPurchaseTime < 0.25f ) return;       // per-caller rate limit (max 4 req/sec)
        if ( string.IsNullOrWhiteSpace( itemId ) || itemId.Length > 64 ) return;
        if ( !ShopCatalog.TryGetPrice( itemId, out var price ) ) return;   // unknown item
        if ( price < 0 || Coins < price ) return;      // cannot afford, or a forged price

        _lastPurchaseTime = 0;
        Coins -= price;                                // the host applies the change once
        GrantItem( caller, itemId );
    }
}

Six checks, in this order

Every [Rpc.Host] method should run these checks in the same order and return on the first one that fails, before it touches any scene object or saved data.

  • Caller identity: read Rpc.Caller (and Rpc.Caller.SteamId) from the transport context. Confirm that this connection owns the component or holds the required team/admin permission.
  • Argument shape and bounds: reject null strings, oversize strings, NaN or Infinity floats (float.IsFinite), negative quantities, and out-of-range slot indices before indexing into any collection.
  • Server-side catalog lookup: look up item prices, weapon damage curves, crafting recipes, and cooldown durations from immutable host tables—never accept numbers passed by the client.
  • World and entity state: verify that the player pawn is alive, not stunned or ragdolled, within interaction radius (Vector3.DistanceBetweenSquared), and has line of sight to the target.
  • Per-caller rate limiting: track TimeSince or a token bucket per connection so a script spamming an RPC 200 times per tick is dropped cheaply before running physics traces.
  • Atomic state mutation: deduct currency and grant the item in a single synchronous host step so two back-to-back packets cannot interleave and spend the same balance twice.

Inventory slot transfers and container locking

Item duplication bugs in roleplay and survival servers almost always happen when a player drags an item between a backpack and a world crate while simultaneously dropping the item or disconnecting. If the client tells the server "put Sword in Crate Slot 0" and separately "clear Backpack Slot 2", a dropped packet or race condition leaves the sword in both places.

Fix this by making every inventory operation a single atomic host swap identified by container NetworkIdent and integer slot index. Lock the source and destination slots inside one host method, verify that both containers are within 3.5 meters of the caller pawn, and swap the references in memory before the next network snapshot.

[Rpc.Host]
public void RequestMoveSlot( Guid targetContainerId, int fromSlot, int toSlot )
{
    if ( !Networking.IsHost ) return;
    var caller = Rpc.Caller;
    if ( caller is null || ( Network.OwnerId != Guid.Empty ? caller.Id != Network.OwnerId : !caller.IsHost ) ) return;
    if ( fromSlot < 0 || fromSlot >= Slots.Count ) return;

    var target = Scene.Directory.FindComponentByGuid<InventoryContainer>( targetContainerId );
    if ( target is null || toSlot < 0 || toSlot >= target.Slots.Count ) return;
    if ( Transform.Position.DistanceSquared( target.Transform.Position ) > 140f * 140f ) return;

    // Atomic host-side swap
    var moving = Slots[fromSlot];
    Slots[fromSlot] = target.Slots[toSlot];
    target.Slots[toSlot] = moving;
}

Movement prediction, hitscan weapon traces, and lag compensation

Clients predict their own movement locally so WASD input feels immediate even on a 70 ms connection, while the host validates each movement step. When a client reports its movement vector or position, compare the delta against MaxWalkSpeed multiplied by Time.Delta (plus a small jitter tolerance for packet bunching). When a client exceeds the physical envelope, snap the pawn back to the last authoritative host transform.

For hitscan and projectile weapons, clients should send only the normalized aim direction and client tick timestamp. The host clamps the aim ray to the pawn eye position, enforces fire-rate cadence, rewinds target hitboxes within a strict lag-compensation cap (typically 150 to 200 ms maximum), and runs Scene.Trace.Ray on the host physics world.

[Rpc.Host]
public void RequestFireWeapon( Vector3 aimDirection, float clientSendTime )
{
    if ( !Networking.IsHost || Rpc.Caller is null || ( Network.OwnerId != Guid.Empty ? Rpc.Caller.Id != Network.OwnerId : !Rpc.Caller.IsHost ) ) return;
    if ( !aimDirection.IsNearZeroLength && !float.IsFinite( aimDirection.Length ) ) return;
    if ( _timeSinceLastShot < FireIntervalSeconds || AmmoInClip <= 0 ) return;

    _timeSinceLastShot = 0;
    AmmoInClip--;

    var dir = aimDirection.Normal;
    var eyePos = OwnerPawn.EyePosition;
    var tr = Scene.Trace.Ray( eyePos, eyePos + dir * MaxRange )
        .IgnoreGameObjectHierarchy( GameObject )
        .Run();

    if ( tr.Hit && tr.GameObject.Components.TryGet<HealthComponent>( out var health ) )
    {
        health.ApplyAuthoritativeDamage( BaseDamage, Rpc.Caller );
    }
}

Choosing between [Sync], [Rpc.Host], and [Rpc.Broadcast]

The wrong one wastes bandwidth or leaves players who join late out of sync. Use [Sync] for state that must match for someone who joins ten minutes later (health, score, whether a door is open, the equipped item ID). Use [Rpc.Host] for requests from a client to the host, and [Rpc.Broadcast] for one-off effects (muzzle flashes, impact decals, UI toasts) that a late joiner does not need to see.

Common mistakes:

  • Sending the outcome ("damage = 50") instead of the intent ("fired along ray").
  • Checking preconditions on the client UI and skipping the host check because the button was disabled.
  • Marking high-frequency cosmetic timers with [Sync] so they dirty the network snapshot 60 times per second.
  • Trusting a string item ID or prefab path without looking it up in a server whitelist.
  • Forgetting that a listen-server host is also a player: run the exact same validation gate when the host invokes an action locally.

Try to break it before you open the server

Before you open a server to the public, connect with a second test account and send bad calls on purpose, from the developer console or a test harness: negative item prices, NaN aim vectors, loops of 100 RPC calls per frame, and container moves from across the map. The host should drop every bad request, or log a rate-limited warning, and no [Sync] balance or inventory slot should change.

Quick reference

SettingValue
State that lasts[Sync] property on a C# Component
One-off events[Rpc.Broadcast] and [Rpc.Host] methods
Who calledRpc.Caller.SteamId (checked by the host session)
Host-only guardif ( !Networking.IsHost ) return;

Tool: Netcode generator.

Unofficial and general. The s&box API changes between versions; check the Facepunch documentation before you copy code.