[英]To get current ip address in c# from client side
在我的应用程序中,我需要获取加载应用程序的用户的 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/");
}
尝试这个:
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!");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.