ASP.NET擷取IP的6種方法

來源:互聯網
上載者:User

服務端:

 

 

//方法一
HttpContext.Current.Request.UserHostAddress; 

//方法二
HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

//方法三
string strHostName = System.Net.Dns.GetHostName();
string clientIPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString();

//方法四(無視代理)
HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

 

用戶端:

 

 

//方法五
var ip = '<!--#echo var="REMOTE_ADDR"-->';
alert("Your IP address is "+ip);

//方法六(無視代理)
function GetLocalIPAddress() 

    var obj = null; 
    var rslt = ""; 
    try 
    { 
        obj = new ActiveXObject("rcbdyctl.Setting"); 
        rslt = obj.GetIPAddress; 
        obj = null; 
    } 
    catch(e) 
    { 
        // 
    } 
     
    return rslt; 

 

22日添加:

 

來自印度的MCT Maulik Patel提供了一種服務端的解決方案,很好:

 

 

if(Context.Request.ServerVariables["HTTP_VIA"]!=null) // using proxy

     ip=Context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();  // Return real client IP.
}
else// not using proxy or can't get the Client IP

     ip=Context.Request.ServerVariables["REMOTE_ADDR"].ToString(); //While it can't get the Client IP, it will return proxy IP.
}

 

備忘:

 

1. 有些代理是不會發給我們真實IP地址的

2. 有些用戶端會因為“header_access deny”的安全設定而不發給我們IP

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.