IPAddress of a login system

前端 未结 6 2516
花落未央
花落未央 2020-12-22 05:42

Using the bellow code .

protected string GetUserIP()
{
    string strUserIP = string.Empty;
    if (HttpContext.Current.Request.ServerVariables[\"HTTP_X_FORW         


        
6条回答
  •  别那么骄傲
    2020-12-22 05:56

    You can find IP Address in a way given below. It works for me :) If you want only one IP then pick up first IP from the list.

    var Dnshost = Dns.GetHostEntry(Dns.GetHostName());
    
    string ipAddress = "";
    
    IPAddress[] ipAddress = Dnshost.AddressList;
    ipAddress = ipAddress[0].ToString();
    

    Here "ipAddress[0]" will give you current IP of system. And if you want all IP's to get then iterate the AddressList as shown below:

    foreach (var ip in Dnshost.AddressList)
     {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    ipAddress = ip.ToString();
                }
     }
    

    NOTE: It will give you the IPv4 Addresses in case of "AddressFamily.InterNetwork" and if you need IPv6 Addresses you will use "AddressFamily.InterNetworkV6".

    Hope it will be helpful for you.

提交回复
热议问题