asp.net中獲取客戶端ip地址的兩種方法
方法一:
///
/// 獲取用戶登錄IP
///
///
string GetIp()
{
//可以透過代理服務器
string userIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (userIP == null || userIP == "")
{
//沒有代理服務器,如果有代理服務器獲取的是代理服務器的IP
userIP = Request.ServerVariables["REMOTE_ADDR"];
}
return userIP;
}
方法二:(很抱歉,這種方法獲取的是服務器端的IP)
//需要using System.Net;
string hostname = Dns.GetHostName();//服務器的用戶名
Response.Write("HostName:"+hostname);
IPAddress[] address = Dns.GetHostAddresses(hostname);//獲取服務器端IP列表,第一IP是address[0]
IPEndPoint ipendpoint = new IPEndPoint(address[0], 1234);
Response.Write("address:"+ipendpoint.Address.ToString());//輸出IP:192.168.0.210,不是127.0.0.1
Response.Write("port:" + ipendpoint.Port.ToString());//輸出1234
Response.Write("endpoint:" + ipendpoint.ToString());//輸出的是192.168.0.210:1234