Home > Net >  how to detect user ip address in unity c#?
how to detect user ip address in unity c#?

Time:09-22

I have to basically create a anti-hack system which detects the user's IP address using Unity API. Is there any easy way to deal with it?

Also I need to check whether the player is using a VPN connection or not. All these has to be done in Unity and C#. Help will be appreciated. Thank you

CodePudding user response:

Send a unique request from your application to your server and see from what IP you see the request on the server.

For the second issue: you can only compare the IP to a list of known proxies.

CodePudding user response:

You can use the below example to expand on it, and adjust it. Not all VPN services may name their interface with "vpn" in it but most will. You might create a Hyper-V or virtual machine (or rent a VPS server) and install some of the VPN apps to see what they name their interfaces.

To get the Public IP, there are some free web APIs that you can call from unity using WWWForm or UnityWebRequest and they return you the public IP in JSON. An example would be at https://www.ipify.org/ or https://www.bigdatacloud.com/client-info-apis/public-ip-address-api

public IEnumerator ScanNetworkInterfaces()
{
    while(Application.isPlaying && SM.CurrentState == GameManagerState.Intro)
    {
        bool foundVPN = false;

        yield return new WaitForSeconds(2);
        foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
        {
            if (ni.OperationalStatus == OperationalStatus.Up)
            {
                if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
                {
                    foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
                    {
                        if (ip != null && ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                        {
                            // My addresses
                            if (ni.Description.ToLower().Contains("vpn"))
                            {
                                foundVPN = true;
                            }
                        }

                        yield return null;
                    }
                }
            }

            yield return null;
        }

        if (foundVPN)
            MainMenuPanel.Instance.ShowWarning("Possibly detected a VPN - you may need to disable it or game will disconnect immediately!");
        else
            MainMenuPanel.Instance.HideWarning();
    }
}
  • Related