Check user's IP address in Unity

· 1 min read
Check user's IP address in Unity

Although Unity does not provide a way on checking user's ip directly, still we can make a script to achieve that:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class PlayerAction : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(getIPRequest("https://api.ipify.org?format=json"));
    }

    private IEnumerator getIPRequest(string uri)
    {
        UnityWebRequest uwr = UnityWebRequest.Get(uri);
        yield return uwr.SendWebRequest();

        if (uwr.isNetworkError || www.isHttpError)
        {
            Debug.Log("Error While Sending: " + uwr.error);
        }
        else
        {
            Debug.Log("Received: " + uwr.downloadHandler.text);
        }
    }
}

The log should just print out the ip address.