获取客户端本地IP地址

时间:2019-04-04 12:19:19

标签: c# asp.net model-view-controller ip

我尝试了许多代码,其中一些在localhost上运行,但是当我发布应用程序时,它返回的是公共IP地址,而不是本地IP地址。并使用了几乎所有可用的serververiables,但未获得所需的结果。得到足够的帮助 Get local IP addressHow to get a user's client IP address in ASP.NET?

string hostName = Dns.GetHostName();
string myIP = Dns.GetHostByName(hostName).AddressList[0].ToString();
return myIP;

var ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
return ip;

var ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
return ip;

var ip = HttpContext.Current.Request.UserHostAddress;
return ip;

string localIP;
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
{
  socket.Connect("8.8.8.8", 65530);
  IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
  localIP = endPoint.Address.ToString();
}
return localIP;

var ip= Dns.GetHostAddresses(Environment.MachineName)[0];

return ip;

0 个答案:

没有答案