如何获取调用ASP.NET页面的服务器的IP地址?我见过有关Response对象的内容,但在c#中我是新手。非常感谢。
答案 0 :(得分:53)
这应该有效:
//this gets the ip address of the server pc
public string GetIPAddress()
{
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); // `Dns.Resolve()` method is deprecated.
IPAddress ipAddress = ipHostInfo.AddressList[0];
return ipAddress.ToString();
}
http://wec-library.blogspot.com/2008/03/gets-ip-address-of-server-pc-using-c.html
OR
//while this gets the ip address of the visitor making the call
HttpContext.Current.Request.UserHostAddress;
http://www.geekpedia.com/KB32_How-do-I-get-the-visitors-IP-address.html
答案 1 :(得分:31)
Request.ServerVariables["LOCAL_ADDR"];
这为IP提供了对多宿主服务器的请求
答案 2 :(得分:13)
上述情况很慢,因为它需要DNS调用(如果一个不可用,显然不会有效)。您可以使用下面的代码获取当前pc的本地IPV4地址及其相应子网掩码的映射:
public static Dictionary<IPAddress, IPAddress> GetAllNetworkInterfaceIpv4Addresses()
{
var map = new Dictionary<IPAddress, IPAddress>();
foreach (var ni in NetworkInterface.GetAllNetworkInterfaces())
{
foreach (var uipi in ni.GetIPProperties().UnicastAddresses)
{
if (uipi.Address.AddressFamily != AddressFamily.InterNetwork) continue;
if (uipi.IPv4Mask == null) continue; //ignore 127.0.0.1
map[uipi.Address] = uipi.IPv4Mask;
}
}
return map;
}
警告:这尚未在Mono中实现
答案 3 :(得分:7)
//this gets the ip address of the server pc
public string GetIPAddress()
{
string strHostName = System.Net.Dns.GetHostName();
//IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); <-- Obsolete
IPHostEntry ipHostInfo = Dns.GetHostEntry(strHostName);
IPAddress ipAddress = ipHostInfo.AddressList[0];
return ipAddress.ToString();
}
答案 4 :(得分:3)
这适用于IPv4:
public static string GetServerIP()
{
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress address in ipHostInfo.AddressList)
{
if (address.AddressFamily == AddressFamily.InterNetwork)
return address.ToString();
}
return string.Empty;
}
答案 5 :(得分:0)
以下快照摘自Mkyong,以显示Google chrome开发人员控制台内的网络标签。在“请求标头” 标签内,您可以看到所有服务器变量的列表,如下所示下方:
下面是几行代码,这些行获取了击中您应用程序的客户端的ipaddress
//gets the ipaddress of the machine hitting your production server
string ipAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (ipAddress == "" || ipAddress == null)
{
//gets the ipaddress of your local server(localhost) during development phase
ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
//Output:
For production server - 122.169.106.247 (random)
For localhost - ::1