Kevin Maxwell
Kevin Maxwell

Reputation: 907

How to get client's external IPv4 address in ASP.NET without using external services?

I'm currently using the following function to get external IPv4 address of my client:

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

Is there any other way to get the same result without using any external website or services?

Upvotes: 0

Views: 2062

Answers (2)

Kevin Maxwell
Kevin Maxwell

Reputation: 907

GET INTERNAL IP ADDRESS

protected string GetInternalIP()
        {
            System.Web.HttpContext context = System.Web.HttpContext.Current;
            string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

            if (!string.IsNullOrEmpty(ipAddress))
            {
                string[] addresses = ipAddress.Split(',');
                if (addresses.Length != 0)
                {
                    return addresses[0];
                }
            }

            return context.Request.ServerVariables["REMOTE_ADDR"];
        }

GET EXTERNAL IP ADDRESS

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

Upvotes: 2

Slashy
Slashy

Reputation: 1881

No. because actually only when you're connecting to a server he can tell you where you come from... so There is not any other option except making a connection to another service. its pretty fast tho... (if this what bothered you..) Hope you understood.

Upvotes: 1

Related Questions