Click here to Skip to main content
15,898,946 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to get the Ip address of the client machine.

i have tried with some code but all time I am getting the Ip address of the server.
How do I get the Ip address of the client machines?
C#
string ip = "";
               string strHostName = "";
               strHostName = System.Net.Dns.GetHostName();
               IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
               IPAddress[] addr = ipEntry.AddressList;
               ip = addr[addr.Length - 1].ToString();



Thanks in advance
Posted
Updated 9-Mar-15 0:57am
v3
Comments
Herman<T>.Instance 9-Mar-15 6:55am    
Windows Forms, WPF, ASP.NET ?
Renjith_R 9-Mar-15 6:56am    
Thanks for your reply, It is a web application

Example
C#
protected void GetUser_IP()
{
    string VisitorsIPAddr = string.Empty;
    if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
    {
        VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
    }
    else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
    {
        VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
    }
    uip.Text = "Your IP is: " + VisitorsIPAddr;
}


More answers needed? -> here[^]
 
Share this answer
 
v2
Comments
phil.o 9-Mar-15 7:17am    
My 5 :)
Renjith_R 9-Mar-15 8:04am    
I already tried this method.It's also returning server ip.When we test from local system it returns ip but if I deployed in server it returns server ip.
Herman<T>.Instance 9-Mar-15 8:08am    
If you don't get the right IP other network restrictions might prevent it
Renjith_R 9-Mar-15 9:34am    
I have tried with this
string ipaddress;
ipaddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (ipaddress == "" || ipaddress == null)
ipaddress = Request.ServerVariables["REMOTE_ADDR"];

it gives result as ::1
Herman<T>.Instance 9-Mar-15 9:36am    
have you tested the functionality against addresses as www.microsoft.com etc?
Sometimes routers prevent giving this information during a request.
Try this,

C#
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"];
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900