0

i am working in asp.net c#, in that i need to get client IP Address to display the client IP. i am hosting my project in IIS 7, using the static ip i can connect my application..

i have to fetch the client IP using the following code. but i can't get correct ip address..

every time i get this ip 192.168.1.18..

i use the following code

private void GetIP()
    {
       string userip = Request.UserHostAddress;
        if (Request.UserHostAddress != null)
        {
            Int64 macinfo = new Int64();
            string macsrc = macinfo.ToString("X");
            if (macsrc == "0")
            {
                if (userip == "127.0.0.1")
                {
                    //ScriptManager.RegisterStartupScript(this, GetType(), "Message", "alert('Visited Localhost')", true);
                    lblIPAddress.Text = userip;
                }
                else
                {
                    lblIPAddress.Text = userip;
                }
            }
        }            
    }

i am also using the following code also but it showing the hosted ip address like 192.168.1.5, where i am hosted my project in server..

public static string GetLocalIPAddress()
    {
        var host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (var ip in host.AddressList)
        {
            //if (ip.AddressFamily == AddressFamily.InterNetwork)
            if (ip.AddressFamily != AddressFamily.InterNetworkV6)
            {
                return ip.ToString();
            }
        }
        throw new Exception("Local IP Address Not Found!");
    }

i need the correct client ip address, any one help

Surya
  • 157
  • 2
  • 7
  • 25
  • 1
    This can be helpful http://stackoverflow.com/questions/735350/how-to-get-a-users-client-ip-address-in-asp-net – Afnan Ahmad Dec 14 '16 at 08:21

2 Answers2

2

try this :

string IP = Request.UserHostAddress;

H. Rashid
  • 176
  • 13
1

It was answered a while ago but theres a similar question here How to Get IP Address? which uses the HTTP_X_FORWARDED_FOR and REMOTE_ADDR request variables. We used this in a project recently and its been working fine

Community
  • 1
  • 1
wolfman1001
  • 171
  • 1
  • 13
  • sir its working fine when you hosted in cloud, but when we hosted in our own server (which is IIS) its not working.. so that i need help sir.. – Surya Dec 14 '16 at 08:53
  • We used this on our IIS server and it worked still works – wolfman1001 Dec 14 '16 at 08:55
  • sir i checked once again, its also shows like this 192.168.1.18 – Surya Dec 14 '16 at 09:16
  • @Surya you could try reading this http://stackoverflow.com/questions/6914457/why-does-servervariableremote-addr-returns-the-server-ip they seem to have the same problem, – wolfman1001 Dec 14 '16 at 09:34
  • it shows 127.0.0.1 when i execute the project, but when i hosted it shows 192.168.1.18.. – Surya Dec 14 '16 at 10:37