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

本文关键字:IP 地址 用户 获取 | 更新日期: 2023-09-27 18:34:51

我想要使用我的网站的客户端的公共IP地址。下面的代码显示了局域网中的本地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 地址。

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

这是我

使用的:

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

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

参考方法 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;
    }
所有这些

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

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

用于 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();
    }

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

这个简单而紧凑的代码来获取访问者的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"];
        }

简单、简短、紧凑。

我有一个扩展方法:

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。 上下文。Request.UserHostAddress 与"REMOTE_ADDR"相同。

但请记住,实际的IP并不一定。

来源:

IIS 服务器变量

链接

我的版本同时处理 ASP.NET 或局域网 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;
}
 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;
        }
    }

在 MVC 5 上,您可以使用以下内容:

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

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

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

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

就用这个......

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

我们连接到为我们提供外部 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

结束功能

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

您可以在以下位置下载 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;
        }
    }
}