Search code examples
c#unity-game-engineipip-address

How to get IP address of device in Unity 2018+?


How to get IP address on C# in program which developing for android device in Unity 2018.2+?

Seems like Network.player.ipAddress is deprecated right now, so I'm looking for a new way.


Solution

  • The Network.player.ipAddress has been deprecated since it is based on the old obsolete Unity networking system.

    If you are using Unity's new uNet Network System, you can use NetworkManager.networkAddress;

    string IP = NetworkManager.singleton.networkAddress;
    

    If you are using raw networking protocol and APIs like TCP/UDP, you have to use the NetworkInterface API to find the IP Address. I use IPManager which has been working for me on both desktop and mobile devices:

    IPv4:

    string ipv4 = IPManager.GetIP(ADDRESSFAM.IPv4);
    

    IPv6:

    string ipv6 = IPManager.GetIP(ADDRESSFAM.IPv6);
    

    The IPManager class:

    using System.Net;
    using System.Net.NetworkInformation;
    using System.Net.Sockets;
    
    public class IPManager
    {
        public static string GetIP(ADDRESSFAM Addfam)
        {
            //Return null if ADDRESSFAM is Ipv6 but Os does not support it
            if (Addfam == ADDRESSFAM.IPv6 && !Socket.OSSupportsIPv6)
            {
                return null;
            }
    
            string output = "";
    
            foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces())
            {
    #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
                NetworkInterfaceType _type1 = NetworkInterfaceType.Wireless80211;
                NetworkInterfaceType _type2 = NetworkInterfaceType.Ethernet;
    
                if ((item.NetworkInterfaceType == _type1 || item.NetworkInterfaceType == _type2) && item.OperationalStatus == OperationalStatus.Up)
    #endif 
                {
                    foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses)
                    {
                        //IPv4
                        if (Addfam == ADDRESSFAM.IPv4)
                        {
                            if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
                            {
                                output = ip.Address.ToString();
                            }
                        }
    
                        //IPv6
                        else if (Addfam == ADDRESSFAM.IPv6)
                        {
                            if (ip.Address.AddressFamily == AddressFamily.InterNetworkV6)
                            {
                                output = ip.Address.ToString();
                            }
                        }
                    }
                }
            }
            return output;
        }
    }
    
    public enum ADDRESSFAM
    {
        IPv4, IPv6
    }