lidgren / lidgren-network-gen3

Lidgren Network Library
https://groups.google.com/forum/#!forum/lidgren-network-gen3
MIT License
1.19k stars 331 forks source link

Unity.Network.externalIP #85

Open levonravel opened 7 years ago

levonravel commented 7 years ago

Hi,

I have been using unity for the past 5 years and noticed in your library with NetUtility.GetIPAddress your assuming that Unity.Network.externalIP will resolve but it wont I have a solution but I am not going to try and botch your code up.. This example will help to get the external IP from unity..

    private string externalIP;
    private string internalIP;

    private void Start()
    {
        StartCoroutine(NetworkSetup());
    }
    public IEnumerator NetworkSetup()
    {
        Network.Connect("127.0.0.1");

        while (Network.player.externalIP == "UNASSIGNED_SYSTEM_ADDRESS")
        {
            time += Time.deltaTime + 0.01f;

            if (time > 10)
            {
                Debug.LogError(" Unable to obtain external ip: Are you sure your connected to the internet");
            }

            yield return null;
        }

        internalIP = Network.player.ipAddress;
        externalIP = Network.player.externalIP;
        Network.Disconnect();
    }

reference is ///

/// Gets my local IPv4 address (not necessarily external) and subnet mask /// public static IPAddress GetMyAddress(out IPAddress mask) { mask = null;

if UNITY_ANDROID || UNITY_STANDALONE_OSX || UNITY_STANDALONE_WIN || UNITY_STANDALONE_LINUX || UNITY_IOS || UNITY

        try
        {
            if (!(UnityEngine.Application.internetReachability == UnityEngine.NetworkReachability.NotReachable))
            {
                return null;
            }
            return IPAddress.Parse(UnityEngine.Network.player.externalIP);
        }
        catch // Catch Access Denied errors
        {
            return null;
        }

endif

        return null;
    }

The method NetworkSetup might look weird as Unity decided to make it some what like a thread. Just think of the method as a thread :). I start off by connecting to myself and loop through while until the address is found or 10 seconds has passed. If everything was successful it will return the externalIP else log as Unable to obtain external ip. You have to make sure to make a connection first before getting the externalIP sort of shitty but that's how unity engineered it.

Best Regards Levon Ravel,