【发布时间】:2019-08-06 08:07:07
【问题描述】:
我正在使用此代码获取访问者我网站的实际 IP 地址,但它返回的公共 IP 地址对我们办公室的每个人都相同,但我想要访问者系统的实际 ipv4 地址。
protected string GetIPAddress()
{
System.Web.HttpContext context = System.Web.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"];
}
protected string GetIPAddressLocal()
{
System.Web.HttpContext context = System.Web.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[addresses.Length-1];
}
}
return context.Request.ServerVariables["REMOTE_ADDR"];
}
public static IPAddress GetIPAddress3(string hostName)
{
Ping ping = new Ping();
var replay = ping.Send(hostName);
if (replay.Status == IPStatus.Success)
{
return replay.Address;
}
return null;
}
private string GetIP()
{
string strHostName = "";
strHostName = System.Net.Dns.GetHostName();
IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
string ipaddress = "";
return ipaddress.ToString();
}
public static string GetUserIP()
{
var ip = (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null
&& System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != "")
? System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
: System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (ip.Contains(","))
ip = ip.Split(',').First().Trim();
return ip;
}
string ipaddress = GetIPAddress();
ViewBag.ip = ipaddress;
ViewBag.ip2= System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.GetValue(1).ToString();
ViewBag.ip3 = Request.ServerVariables["REMOTE_ADDR"];
ViewBag.ip4 = System.Web.HttpContext.Current.Request.UserHostAddress;
ViewBag.ip5 = GetIPAddress3(System.Net.Dns.GetHostName());
ViewBag.ip6 = GetIP();
ViewBag.ip7 = GetUserIP();
我使用了多个函数,它返回 servers ip address or the public ip address which is same for all the users. It doesnt 返回用户系统的实际 IP 地址。
【问题讨论】:
-
应该是这样,内部IP地址就是这样。无论您使用 10.x、172.x 还是 192.x,因为您无法路由到它,或者以任何方式使用它,唯一的地址是公共地址。
-
即使您确实获得了用户的内部 IP 地址,它也不会是唯一的。路由器转换 IP 地址的全部目的是允许多个网络在内部重用相同的范围。
-
服务器唯一能看到的是通过流量的最后一个 NATing 路由器或代理的公共 IP 地址。 *FORWARDED_FOR 标头可以伪造;不要依赖他们
-
您认为为什么需要这样做?可能有更好的方法来满足您的业务需求。
标签: c# asp.net http c#-4.0 network-programming