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

时间:2013-10-10 02:19:52

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我想要使用我网站的客户的公共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地址。

16 个答案:

答案 0 :(得分:70)

这就是我使用的:

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

答案 1 :(得分:24)

您可以使用“HTTP_X_FORWARDED_FOR”或“REMOTE_ADDR”标头属性。

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;
    }

答案 2 :(得分:11)

所有这些建议的组合,以及它们背后的原因。随意添加更多测试用例。如果获得客户端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;
    }

答案 3 :(得分:10)

该代码为您提供服务器的IP地址,而不是访问您网站的客户的地址。将HttpContext.Current.Request.UserHostAddress属性用于客户端的IP地址。

答案 4 :(得分:9)

对于Web应用程序(ASP.NET MVC和WebForm)

/// <summary>
/// Get current user ip address.
/// </summary>
/// <returns>The IP Address</returns>
public static string GetUserIPAddress()
{
    var context = System.Web.HttpContext.Current;
    string ip = String.Empty;

    if (context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
        ip = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
    else if (!String.IsNullOrWhiteSpace(context.Request.UserHostAddress))
        ip = context.Request.UserHostAddress;

    if (ip == "::1")
        ip = "127.0.0.1";

    return ip;
}

对于Windows应用程序(Windows窗体,控制台,Windows服务,...)

    static void Main(string[] args)
    {
        HTTPGet req = new HTTPGet();
        req.Request("http://checkip.dyndns.org");
        string[] a = req.ResponseBody.Split(':');
        string a2 = a[1].Substring(1);
        string[] a3=a2.Split('<');
        string a4 = a3[0];
        Console.WriteLine(a4);
        Console.ReadLine();
    }

答案 5 :(得分:6)

这些代码片段中有很多都非常庞大,可能会让寻求帮助的新程序员感到困惑。

这个简单而紧凑的代码如何获取访问者的IP地址?

string ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (string.IsNullOrEmpty(ip))
        {
            ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        }

简单,简洁,紧凑。

答案 6 :(得分:4)

我有一个扩展方法:

public static string GetIp(this HttpContextBase context)
{
    if (context == null || context.Request == null)
        return string.Empty;

    return context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] 
           ?? context.Request.UserHostAddress;
}

注意:“HTTP_X_FORWARDED_FOR”用于代理后面的ip。 context.Request.UserHostAddress与“REMOTE_ADDR”相同。

但请记住,实际的IP并不是必需的。

来源:

IIS Server Variables

Link

答案 7 :(得分:3)

我的版本处理ASP.NET或LAN IP:

/** 
 * Get visitor's ip address.
 */
public static string GetVisitorIp() {
    string ip = null;
    if (HttpContext.Current != null) { // ASP.NET
        ip = string.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"])
            ? HttpContext.Current.Request.UserHostAddress
            : HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    }
    if (string.IsNullOrEmpty(ip) || ip.Trim() == "::1") { // still can't decide or is LAN
        var lan = Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(r => r.AddressFamily == AddressFamily.InterNetwork);
        ip = lan == null ? string.Empty : lan.ToString();
    }
    return ip;
}

答案 8 :(得分:2)

 private string GetClientIpaddress()
    {
        string ipAddress = string.Empty;
        ipAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (ipAddress == "" || ipAddress == null)
        {
            ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            return ipAddress;
        }
        else
        {
            return ipAddress;
        }
    }

答案 9 :(得分:2)

在MVC 5上,您可以使用:

string cIpAddress = Request.UserHostAddress; //Gets the client ip address

string cIpAddress = Request.ServerVariables["REMOTE_ADDR"]; //Gets the client ip address

答案 10 :(得分:1)

在MVC中IP可以通过以下代码获得

string ipAddress = Request.ServerVariables["REMOTE_ADDR"];

答案 11 :(得分:1)

string IP = HttpContext.Current.Request.Params["HTTP_CLIENT_IP"] ?? HttpContext.Current.Request.UserHostAddress;

答案 12 :(得分:1)

只需使用..................

public string GetIP()
{
   string externalIP = "";
   externalIP = (new WebClient()).DownloadString("http://checkip.dyndns.org/");
   externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")).Matches(externalIP)[0].ToString();
   return externalIP;
}

答案 13 :(得分:0)

我们连接到提供外部IP地址的服务器,并尝试从返回的HTML页面解析IP。但是,当服务器对这些页面进行小的更改或删除它们时,这些方法就会停止正常工作。

这是一种使用已经存在多年的服务器获取外部IP地址并快速返回简单响应的方法... https://www.codeproject.com/Tips/452024/Getting-the-External-IP-Address

Private string getExternalIp()
{
try
{
    string externalIP;
    externalIP = (new 
    WebClient()).DownloadString("http://checkip.dyndns.org/");
    externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
                 .Matches(externalIP)[0].ToString();
    return externalIP;
}
catch { return null; }
}

VB.NET

Imports System.Net
Private Function GetExternalIp() As String
Try
    Dim ExternalIP As String
    ExternalIP = (New WebClient()).DownloadString("http://checkip.dyndns.org/")
    ExternalIP = (New Regex("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")) _
                 .Matches(ExternalIP)(0).ToString()
    Return ExternalIP
Catch
    Return Nothing
End Try

结束功能

答案 14 :(得分:0)

lblmessage.Text =Request.ServerVariables["REMOTE_HOST"].ToString();

答案 15 :(得分:0)

您可以在以下位置下载 xNet:https://drive.google.com/open?id=1fmUosINo8hnDWY6s4IV4rDnHKLizX-Hq

首先需要导入xNet,代码:

using xNet;

代码:

void LoadpublicIP()
{
    HttpRequest httprequest = new HttpRequest();
    String HTML5 = httprequest.Get("https://whoer.net/").ToString();
    MatchCollection collect = Regex.Matches(HTML5, @"<strong data-clipboard-target="".your-ip(.*?)</strong>", RegexOptions.Singleline);
    foreach (Match match in collect)
    {
        var val = Regex.Matches(match.Value, @"(?<ip>(\d|\.)+)");
        foreach (Match m in val)
        {
            richTextBox1.Text = m.Groups[2].Value;
        }
    }
}