Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET: get external IP address

Tags:

c#

asp.net

ip

I developed site. I need to get IP of site visitors. I try to use Request, but it have only internal IP:

Response.Write(Request.ServerVariables["REMOTE_ADDR"]);

I looked all keys in Server Variables collection - the same result:

foreach (string var in Request.ServerVariables)
{
    Response.Write(Request[var]);
}

How can I get external IP address?

like image 431
Elena Avatar asked May 08 '26 08:05

Elena


2 Answers

You can use it to get External (public) 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; }
    }
like image 171
Imran Athar Avatar answered May 09 '26 21:05

Imran Athar


This it part of my implementation for WebTracking. So here you go a snippet for IpAddress retrieval. You can read more about the Server Variables at Wikipedia.

    /// <summary>
    /// Get ip address from request
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    private string GetIpAddress(HttpRequest request)
    {
        if (request.ServerVariables.IsNull()) return null;

        var _realAddress = request.ServerVariables[@"HTTP_X_FORWARDED_FOR"];
        if (_realAddress.IsNullOrEmpty())
        {
            _realAddress = request.ServerVariables[@"HTTP_FORWARDED"];
        }
        if (_realAddress.IsNullOrEmpty())
        {
            _realAddress = request.ServerVariables[@"REMOTE_ADDR"];
        }

        return _realAddress;
    }
like image 29
Marjan Nikolovski Avatar answered May 09 '26 21:05

Marjan Nikolovski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!