unity-game-enginenetwork-programmingportforwardingnatnetwork-connection

Question for Unity3d Developement platform:'NatUtility' does not contain a definition for 'DeviceLost'


I already added using Mono.Nat; but apparently Unity said

'NatUtility' does not contain a definition for 'DeviceLost'"

which confuses me. To the point where I literally copied 1:1 with the API Reference. I'm quite in confusion.

code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mono.Nat;

public class UPnP_PortForwardingBS : MonoBehaviour
{
    public void Start()
    {
        // Hook into the events so you know when a router has been detected or has gone offline
        NatUtility.DeviceFound += DeviceFound;
        NatUtility.DeviceLost += DeviceLost;

        // Start searching for upnp enabled routers
        NatUtility.StartDiscovery();
    }

    void DeviceFound(object sender, DeviceEventArgs args)
    {
        // This is the upnp enabled router
        INatDevice device = args.Device;

        // Create a mapping to forward external port 3000 to local port 1500
        device.CreatePortMap(new Mapping(Protocol.Tcp, 1500, 3000));

        // Retrieve the details for the port map for external port 3000
        Mapping m = device.GetSpecificMapping(Protocol.Tcp, 3000);

        // Get all the port mappings on the device and delete them
        foreach (Mapping mp in device.GetAllMappings())
            device.DeletePortMap(mp);

        // Get the external IP address
        var externalIP = device.GetExternalIP();
    }

    private void DeviceLost(object sender, DeviceEventArgs args)
    {
        INatDevice device = args.Device;

        //Debug.Log("Device Lost");
        //Debug.Log("Type: {0}", device.GetType().Name);
    }
}

Solution

  • Please see Mono.Nat GitHub release page:

    • Removed NatUtility.DeviceLost as it was never a usable event.
    • Added the ability to manually pass messages into Mono.Nat if another part of the application has already bound to the normal upnp listening port.
    • Improved logging via Logger.Factory
    • Searchers are disposed when NatUtility.StopDiscovery is invoked, and (re-)created when NatUtility.StartDiscovery is invoked. In addition any previously detected devices are cleared when StopDiscovery is invoked.