首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在C#中获取用户的公网IP地址

如何在C#中获取用户的公网IP地址
EN

Stack Overflow用户
提问于 2013-10-10 10:19:52
回答 16查看 169.4K关注 0票数 54

我想知道使用我网站的客户的公共IP地址。下面的代码显示了LAN中的本地IP,但我想要客户端的公共IP。

//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地址。

EN

回答 16

Stack Overflow用户

发布于 2013-10-10 10:58:22

这是我使用的:

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的标签的名称。

票数 72
EN

Stack Overflow用户

发布于 2013-11-25 21:36:51

您可以使用"HTTP_X_FORWARDED_FOR“或"REMOTE_ADDR”header属性。

Machine Syntax blog .引用方法GetVisitorIPAddress

    /// <summary>
    /// method to get Client ip address
    /// </summary>
    /// <param name="GetLan"> set to true if want to get local(LAN) Connected ip address</param>
    /// <returns></returns>
    public static string GetVisitorIPAddress(bool GetLan = false)
    {
        string visitorIPAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

        if (String.IsNullOrEmpty(visitorIPAddress))
            visitorIPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

        if (string.IsNullOrEmpty(visitorIPAddress))
            visitorIPAddress = HttpContext.Current.Request.UserHostAddress;

        if (string.IsNullOrEmpty(visitorIPAddress) || visitorIPAddress.Trim() == "::1")
        {
            GetLan = true;
            visitorIPAddress = string.Empty;
        }

        if (GetLan && string.IsNullOrEmpty(visitorIPAddress))
        {
                //This is for Local(LAN) Connected ID Address
                string stringHostName = Dns.GetHostName();
                //Get Ip Host Entry
                IPHostEntry ipHostEntries = Dns.GetHostEntry(stringHostName);
                //Get Ip Address From The Ip Host Entry Address List
                IPAddress[] arrIpAddress = ipHostEntries.AddressList;

                try
                {
                    visitorIPAddress = arrIpAddress[arrIpAddress.Length - 2].ToString();
                }
                catch
                {
                    try
                    {
                        visitorIPAddress = arrIpAddress[0].ToString();
                    }
                    catch
                    {
                        try
                        {
                            arrIpAddress = Dns.GetHostAddresses(stringHostName);
                            visitorIPAddress = arrIpAddress[0].ToString();
                        }
                        catch
                        {
                            visitorIPAddress = "127.0.0.1";
                        }
                    }
                }

        }


        return visitorIPAddress;
    }
票数 24
EN

Stack Overflow用户

发布于 2014-10-25 03:07:16

所有这些建议的组合,以及背后的原因。您也可以随意添加更多的测试用例。如果获取客户端IP是最重要的,那么您可能希望获得所有这些IP,然后运行一些比较,比较哪个结果可能更准确。

简单的检查所有建议在这个帖子加上一些我自己的代码…

    using System.IO;
    using System.Net;

    public string GetUserIP()
    {
        string strIP = String.Empty;
        HttpRequest httpReq = HttpContext.Current.Request;

        //test for non-standard proxy server designations of client's IP
        if (httpReq.ServerVariables["HTTP_CLIENT_IP"] != null)
        {
            strIP = httpReq.ServerVariables["HTTP_CLIENT_IP"].ToString();
        }
        else if (httpReq.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
        {
            strIP = httpReq.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
        }
        //test for host address reported by the server
        else if
        (
            //if exists
            (httpReq.UserHostAddress.Length != 0)
            &&
            //and if not localhost IPV6 or localhost name
            ((httpReq.UserHostAddress != "::1") || (httpReq.UserHostAddress != "localhost"))
        )
        {
            strIP = httpReq.UserHostAddress;
        }
        //finally, if all else fails, get the IP from a web scrape of another server
        else
        {
            WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
            using (WebResponse response = request.GetResponse())
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                strIP = sr.ReadToEnd();
            }
            //scrape ip from the html
            int i1 = strIP.IndexOf("Address: ") + 9;
            int i2 = strIP.LastIndexOf("</body>");
            strIP = strIP.Substring(i1, i2 - i1);
        }
        return strIP;
    }
票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19285957

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档