如何获取调用我的 ASP.NET 页面的服务器的 IP 地址?我见过关于 Response 对象的东西,但在 c# 中我很新。万分感谢。
Jergason
问问题
86233 次
6 回答
66
这应该有效:
//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
或者
//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
于 2009-03-14T19:20:43.280 回答
40
Request.ServerVariables["LOCAL_ADDR"];
这为多宿主服务器提供了请求进入的 IP
于 2012-07-18T13:22:44.073 回答
14
上面的方法很慢,因为它需要一个 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 中实现
于 2010-02-10T19:08:17.990 回答
8
//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();
}
于 2011-04-04T11:30:27.967 回答
6
这适用于 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;
}
于 2015-06-15T12:56:44.737 回答
0
下面的快照取自Mkyong以在谷歌浏览器中显示开发人员控制台内的网络选项卡。在“请求标头”选项卡中,您可以看到所有服务器变量的列表,如下所示:
下面是几行代码,它们获取访问您的应用程序的客户端的 IP 地址
//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
于 2019-09-05T11:17:06.863 回答