如何在C#中获取用户的公共IP地址 [英] How to get the public IP address of a user in C#

查看:34
本文介绍了如何在C#中获取用户的公共IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要使用我网站的客户端的公共 IP 地址.下面的代码显示的是局域网内的本地IP,但我要的是客户端的公网IP.

I want the public IP address of the client who is using my website. The code below is showing the local IP in the LAN, but I want the public IP of the client.

//get mac address
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
String sMacAddress = string.Empty;
foreach (NetworkInterface adapter in nics)
{
    if (sMacAddress == String.Empty)// only return MAC Address from first card  
    {
        IPInterfaceProperties properties = adapter.GetIPProperties();
        sMacAddress = adapter.GetPhysicalAddress().ToString();
    }
}
// To Get IP Address


string IPHost = Dns.GetHostName();
string IP = Dns.GetHostByName(IPHost).AddressList[0].ToString();

输出:

IP 地址:192.168.1.7

Ip Address : 192.168.1.7

请帮我获取公共IP地址.

Please help me to get the public IP address.

推荐答案

这是我使用的:

protected void GetUser_IP()
{
    string VisitorsIPAddr = string.Empty;
    if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
    {
        VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
    }
    else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
    {
        VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
    }
    uip.Text = "Your IP is: " + VisitorsIPAddr;
}

uip"是aspx页面中显示用户IP的标签名称.

"uip" is the name of the label in the aspx page that shows the user IP.

这篇关于如何在C#中获取用户的公共IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆