1

When window is loading IP will generate I want to call the IP in Code Behind page load

JavaScript

<script type="text/javascript">
        window.onload = function () {
            var script = document.createElement("script");
            script.type = "text/javascript";
            script.src = "https://api.ipify.org?format=jsonp&callback=DisplayIP";
            document.getElementsByTagName("head")[0].appendChild(script);
        };
        function DisplayIP(response) {
            document.getElementById("<%=ipaddress.ClientID%>").innerHTML = "Your IP Address is " + response.ip;
        }
</script>

Label

<span id = "ipaddress" runat="server"></span>

Code behind file:

protected void Page_Load(object sender, EventArgs e)
{

    MyIP = ipaddress.InnerText;
    url = "http://ip-api.com/xml/" + MyIP + "";
}

Empty

1 Answers1

0

The reason why ipaddress does not contain the expected value is because the Page_Load event occurs before the execution of Javascript. You could try to use the TextChanged event of your textbox instead.

Alternatively, you could obtain the client's IP address directly in the code-behind, without using javascript (see here).

Here is one of the suggested solutions (taken from the link above):

protected string GetIPAddress()
{
    System.Web.HttpContext context = System.Web.HttpContext.Current; 
    string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

    if (!string.IsNullOrEmpty(ipAddress))
    {
        string[] addresses = ipAddress.Split(',');
        if (addresses.Length != 0)
        {
            return addresses[0];
        }
    }

    return context.Request.ServerVariables["REMOTE_ADDR"];
}
Andrew Bedford
  • 176
  • 1
  • 7