我在用C#獲取完整的IP地址時遇到了一些問題。當我通過點擊按鈕調用C#web方法時,它會在JavaScript警告框中顯示(或應該)IP地址。我得到的而不是IP地址是:: 1。我通過Visual Studio 2015社區運行它。這裏是我的代碼:C#沒有顯示完整的IP地址
[WebMethod]
public string getIPAddress()
{
// this method gets the ip address by using the server variables
// in C# to capture the data from the client
HttpContext context = 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"];
}
並處理該按鈕單擊方法:
// display the ip address to the user if the button is clicked (display it via a javascript alert box)
public void IpAddress(object sender, EventArgs e)
{
Data d = new Data();
Response.Write("<script type=\"text/javascript\">alert('" + d.getIPAddress() + "');</script>");
}
任何幫助,將不勝感激。謝謝!
這是一個完整的IP地址;它是IPv6本地主機。 – SLaks
有什麼方法可以獲得IPv4地址或者這是不可能的? – user2101411