Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have hosted my mvc application in server "testserver".
and i am trying to get client IP address but that is not getting value displaying null.


Could you please help me how to get ip address.
same code is getting ipaddress in local machine but no from server.

What I have tried:

I have tried
private string GetClientIPAddress()
{
string clientIPAddress = string.Empty;
try
{
clientIPAddress = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.GetValue(0).ToString();
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)
{
clientIPAddress = Convert.ToString(IP);
}
}
}
catch
{
clientIPAddress = "";
}
return clientIPAddress;
}

working in local but not in server.
Posted
Updated 15-Mar-18 23:19pm
Comments
F-ES Sitecore 16-Mar-18 5:09am    
This is a very frequently asked question, please do basic research like using google before you ask a question.

Spoiler: the answer is that you can't, and it doesn't matter how many times the question is asked the answer stays the same.

1 solution

C# code is executed on the server, not the client - so any attempts to access a network adaptor will access the server information, not the client.
You need to use the HttpRequest.UserHostAddress Property (System.Web)[^] instead.
 
Share this answer
 
v2
Comments
DGKumar 16-Mar-18 7:32am    
I have tried to use but getting ::1 or empty from host server
private char[] HEADER_SEPARATOR = { ',' };



string clientIPAddress = string.Empty;
try
{
if (null == HttpContext.Current || null == HttpContext.Current.Request)
return null;


var request = HttpContext.Current.Request;
var forwards = request.Headers.Get("X-Forwarded-For");
if (!string.IsNullOrEmpty(forwards))
{
var values = forwards.Split(HEADER_SEPARATOR, 2);
return values[0];
}

/*else*/
clientIPAddress= request.UserHostAddress;
}
OriginalGriff 16-Mar-18 7:42am    
Try looking at
string forwardedListInCSV = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

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