54

I want the public IP address of the client who is using my website. The code below is showing the local IP in the LAN, but I want the public IP of the client.

//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();

Output:

Ip Address : 192.168.1.7

Please help me to get the public IP address.

ataravati
  • 8,891
  • 9
  • 57
  • 89
Neeraj Mehta
  • 1,675
  • 2
  • 22
  • 45
  • @Parker Although his code makes it look like a duplicate, he is really asking about ASP.NET and getting the client address, which is very doable. – Scott Chamberlain Oct 10 '13 at 02:28
  • Hi there, is there any reason why you unaccepted my answer after nearly one and a half year? If you did it on purpose would be nice to have your comment. Thanks. – FeliceM Mar 18 '15 at 11:58

16 Answers16

72

This is what I use:

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" is the name of the label in the aspx page that shows the user IP.

FeliceM
  • 4,163
  • 9
  • 48
  • 75
  • Object reference not set to an instance of an object. if (HttpContext.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null) – Neeraj Mehta Oct 10 '13 at 12:41
  • String direction = ""; WebRequest request = WebRequest.Create("http://checkip.dyndns.org/"); using (WebResponse response = request.GetResponse()) using (StreamReader stream = new StreamReader(response.GetResponseStream())) { direction = stream.ReadToEnd(); } //Search for the ip in the html int first = direction.IndexOf("Address: ") + 9; int last = direction.LastIndexOf("

    "); direction = direction.Substring(first, last - first); return direction; This helps me but it is taking from other website if in case that website is down than what?

    – Neeraj Mehta Oct 10 '13 at 13:01
  • What do you mean? Have you tested the code I gave in my answer? It is working on all my websites. Let me know where have you put the code. That could be the problem – FeliceM Oct 10 '13 at 13:11
  • 5
    this method would be better if it returned the IP instead of outputting it to an asp.net label control – hanzolo Mar 18 '15 at 22:24
  • For me it returns the IP of the machine where my site is hosted. Exactly the same as string ip = Request.ServerVariables["REMOTE_ADDR"]; – Иво Недев Mar 24 '15 at 10:09
24

You can use "HTTP_X_FORWARDED_FOR" or "REMOTE_ADDR" header attribute.

Refer method GetVisitorIPAddress from Machine Syntax blog .

    /// <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;
    }
shamcs
  • 629
  • 6
  • 15
  • I have tried on Azure VM and `arrIpAddress[0]` contains IPv6 address what is proper `String`, therefore `Catch` is not executed and in the result we get IPv6 instead of local IPv4 or 127.0.0.1. IPv4 is kept in `arrIpAddress[1]`. How shall I deal with this in order to get IPv4 instead in such cases? – Megrez7 Feb 16 '17 at 00:26
12

Combination of all of these suggestions, and the reasons behind them. Feel free to add more test cases too. If getting the client IP is of utmost importance, than you might wan to get all of theses are run some comparisons on which result might be more accurate.

Simple check of all suggestions in this thread plus some of my own code...

    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;
    }
John Suit
  • 1,254
  • 12
  • 17
10

That code gets you the IP address of your server not the address of the client who is accessing your website. Use the HttpContext.Current.Request.UserHostAddress property to the client's IP address.

shf301
  • 31,086
  • 2
  • 52
  • 86
9

For Web Applications ( ASP.NET MVC and 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;
}

For Windows Applications ( Windows Form, Console, Windows Service , ... )

    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();
    }
Peyman Mehrabani
  • 619
  • 6
  • 17
6

So many of these code snippets are really big and could confuse new programmers looking for help.

How about this simple and compact code to fetch the IP address of the visitor?

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

Simple, short and compact.

Jason Towne
  • 8,014
  • 5
  • 54
  • 69
user3100230
  • 61
  • 1
  • 1
4

I have an extension method:

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

Note: "HTTP_X_FORWARDED_FOR" is for ip behind proxy. context.Request.UserHostAddress is identical to "REMOTE_ADDR".

But bear in mind it is not necessary the actual IP though.

Sources:

IIS Server Variables

Link

Stephen Zeng
  • 2,748
  • 21
  • 18
4

My version handles both ASP.NET or LAN IPs:

/** 
 * 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;
}
CJLopez
  • 5,495
  • 2
  • 18
  • 30
Marshal
  • 4,452
  • 1
  • 23
  • 15
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;
        }
    }
nazar tvm
  • 99
  • 7
2

On MVC 5 you can use this:

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

or

string cIpAddress = Request.ServerVariables["REMOTE_ADDR"]; //Gets the client ip address
César León
  • 2,941
  • 1
  • 21
  • 18
1

In MVC IP can be obtained by the following Code

string ipAddress = Request.ServerVariables["REMOTE_ADDR"];
BonDaviD
  • 961
  • 3
  • 11
  • 27
1
string IP = HttpContext.Current.Request.Params["HTTP_CLIENT_IP"] ?? HttpContext.Current.Request.UserHostAddress;
GorkemHalulu
  • 2,925
  • 1
  • 27
  • 25
1

just use this..................

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;
}
Jeetendra Negi
  • 443
  • 3
  • 3
0

We connect to servers that give us our external IP address and try to parse the IP from returning HTML pages. But when servers make small changes on these pages or remove them, these methods stop working properly.

Here is a method that takes the external IP address using a server which has been alive for years and returns a simple response rapidly... 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

End Function

Gamonki
  • 21
  • 1
  • 1
  • 6
0
lblmessage.Text =Request.ServerVariables["REMOTE_HOST"].ToString();
tarzanbappa
  • 4,930
  • 22
  • 75
  • 117
Vipin G
  • 169
  • 1
  • 8
  • 2
    Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation [would greatly improve](//meta.stackexchange.com/q/114762) its long-term value by showing *why* this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you've made. – Toby Speight Oct 04 '17 at 08:05
0

You can download xNet at: https://drive.google.com/open?id=1fmUosINo8hnDWY6s4IV4rDnHKLizX-Hq

First, you need import xNet, code:

using xNet;

Code:

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;
        }
    }
}
Josef
  • 2,869
  • 2
  • 22
  • 23
BiBi
  • 31
  • 1
  • 2