在我的应用程序中,我需要获取加载应用程序的用户的ip地址
我尝试了各种方法来获取IP地址。但是,当尝试加载应用程序时,没有获取当前的IP地址。
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"];
}
string ipAddress=Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(o => o.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).First().ToString()
string ipAddress=(HttpContext.Current.Request.UserHostAddress != null) ? HttpContext.Current.Request.UserHostAddress : null;
using (WebClient wc = new WebClient())
{
ipAddress = wc.DownloadString("https://api.ipify.org/");
}
答案 0 :(得分:-1)
尝试一下:
public static string GetLocalIPAddress()
{
var isConnected = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
if(isConnected){
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
}
throw new Exception("No network adapters with an IPv4 address in the system!");
}