簡體   English   中英

從客戶端獲取 C# 中的當前 ip 地址

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM