marcosfandrade
marcosfandrade

Reputation: 27

Get Public client IP in C#/.net without external service

How i get public client IP in C# without external api/service

I tried use this code. But, not success.

string ipAddress = Response.HttpContext.Connection.RemoteIpAddress.ToString();
        if(ipAddress == "::1")
        {
            ipAddress = Dns.GetHostEntry(Dns.GetHostName()).AddressList[1].ToString();
        }
        Console.WriteLine(ipAddress);

Upvotes: 0

Views: 2430

Answers (1)

Faisal
Faisal

Reputation: 82

on ASP.NET Follow This Method:

Public string GetIp()  
{  
string ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];  
if (string.IsNullOrEmpty(ip))  
{  
   ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];  
}  
return ip;  
} 

otherwise use below method:

Public string GetIp()  {
        string IPAddress = "";
            IPHostEntry Host = default(IPHostEntry);
            string Hostname = null;
            Hostname = System.Environment.MachineName;
            Host = Dns.GetHostEntry(Hostname);
            foreach (IPAddress IP in Host.AddressList)
            {
                if (IP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    IPAddress = Convert.ToString(IP);
                }
            }

            return IPAddress;
}

Please up-vote if you found this helpful.

Upvotes: 0

Related Questions