<%@ Page Language="C#" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.Net.Sockets" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
//获取客户端的IPv4
lblClientIPv4.Text = GetClientIPv4();
//获取客户端的IPv6如果获取不到IPv6将自动获取IPv4
lblClientIPv6.Text = GetClientIpPv6();
//获取服务器的IPv6
lblServersIPv6.Text = GetServerIPv6();
//获取服务器的IPv4
lblServersIPv4.Text = GetServersIPv4();
}
//判断客户端有没有使用代理使用代理返回true,没有使用代理返回false
private bool IsProxy()
{
bool flag = false;
if (Context.Request.ServerVariables["HTTP_VIA"] != null) // 使用了代理
{
flag = true;
}
else //没有使用代理
{
flag = false;
}
return flag;
}
//获取客户端的IPv6如果获取不到IPv6将自动获取IPv4
private string GetClientIpPv6()
{
string ipv6 = string.Empty;
//ipv6 = Request.UserHostAddress;
if (IsProxy())//客户端有使用代理
{
ipv6 = Context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else//客户端没有使用代理
{
ipv6 = Context.Request.ServerVariables["REMOTE_ADDR"].ToString();
}
return ipv6;
}
//获取客户端的IPv4
public string GetClientIPv4()
{
string ipv4 = String.Empty;
foreach (IPAddress IPA in Dns.GetHostAddresses(HttpContext.Current.Request.UserHostAddress))
{
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
ipv4 = IPA.ToString();
break;
}
}
if (ipv4 != String.Empty)
{
return ipv4;
}
foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
ipv4 = IPA.ToString();
break;
}
}
return ipv4;
}
//获取服务器的IPv6
private string GetServerIPv6()
{
string ipv6 = string.Empty;
ipv6 = Dns.GetHostAddresses(Dns.GetHostName())[0].ToString();
return ipv6;
}
//获取服务器的IPv4
private string GetServersIPv4()
{
string ipv4 = string.Empty;
ipv4 = Dns.GetHostAddresses(Dns.GetHostName())[1].ToString();
return ipv4;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
ClientIPv4:
<asp:Label ID="lblClientIPv4" runat="server"></asp:Label>
<br/>
ClientIPv6:
<asp:Label ID="lblClientIPv6" runat="server"></asp:Label>
<br />
ServersIPv4:
<asp:Label ID="lblServersIPv4" runat="server"></asp:Label>
<br />
ServersIPv6:
<asp:Label ID="lblServersIPv6" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
c# web获取ip
最新推荐文章于 2023-07-27 16:48:16 发布