C# 获取客户端IPv4地址的示例代码
网上找了一些获取客户端IP的方法,但本地测试时,返回的是IPv6的表示方法"::1":
Host文件里面:# ::1 localhost
后来找了获取IPv4的方法就可以了,比较好用:
public static string GetClientIPv4Address()
{
string ipv4 = String.Empty;
foreach (IPAddress ip in Dns.GetHostAddresses(GetClientIP()))
{
if (ip.AddressFamily.ToString() == "InterNetwork")
{
ipv4 = ip.ToString();
break;
}
}
if (ipv4 != String.Empty)
{
return ipv4;
}
// 利用 Dns.GetHostEntry 方法,由获取的 IPv6 位址反查 DNS 纪录,
// 再逐一判断何者为 IPv4 协议,即可转为 IPv4 位址。
foreach (IPAddress ip in Dns.GetHostEntry(GetClientIP()).AddressList)
//foreach (IPAddress ip in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (ip.AddressFamily.ToString() == "InterNetwork")
{
ipv4 = ip.ToString();
break;
}
}
return ipv4;
}
public static string GetClientIP()
{
if (null == HttpContext.Current.Request.ServerVariables["HTTP_VIA"])
{
return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
else
{
return HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
}
}
以上是 C# 获取客户端IPv4地址的示例代码 的全部内容, 来源链接: utcz.com/z/345942.html