54

Web サイトを使用しているクライアントのパブリック 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 アドレスを取得するのを手伝ってください。

4

16 に答える 16

72

これは私が使用するものです:

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」は、ユーザー IP を表示する aspx ページのラベルの名前です。

于 2013-10-10T02:58:22.490 に答える
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;
    }
于 2013-11-25T13:36:51.380 に答える
12

これらすべての提案の組み合わせと、その背後にある理由。テストケースも自由に追加してください。クライアント 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;
    }
于 2014-10-24T19:07:15.943 に答える
10

そのコードは、Web サイトにアクセスしているクライアントのアドレスではなく、サーバーの IP アドレスを取得します。HttpContext.Current.Request.UserHostAddressプロパティをクライアントの IP アドレスに使用します。

于 2013-10-10T02:27:17.360 に答える
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();
    }
于 2015-04-30T09:52:19.063 に答える
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"];
        }

シンプル、ショート、コンパクト。

于 2013-12-13T17:00:52.580 に答える
2

MVC 5 では、これを使用できます。

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

また

string cIpAddress = Request.ServerVariables["REMOTE_ADDR"]; //Gets the client ip address
于 2016-12-12T18:35:05.187 に答える
1

In MVC IP can be obtained by the following Code

string ipAddress = Request.ServerVariables["REMOTE_ADDR"];
于 2013-10-10T06:21:15.577 に答える
1
string IP = HttpContext.Current.Request.Params["HTTP_CLIENT_IP"] ?? HttpContext.Current.Request.UserHostAddress;
于 2014-07-15T06:36:52.993 に答える
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;
}
于 2015-02-25T20:09:13.220 に答える