In one of the previous question, you can find how to get client ip address using javascript or jquery, but in this article, I am going to provide you server side solution to get client ip address using C#, local or public IP, we will be using Console Application example here, but you can use the same code in .NET Web-Forms or MVC or in .NET Core.

Get Client IP in ASP.NET Core

In ASP.NET Core, you can simply use below code to get Client IP Address

var ipAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString();

Note: The above code, will return localhost address when working locally.

If you are using load balancer, then you can manually read the 'X-Forwarded-For' header, so you can use below code.

IPAddress ip;
var headers = Request.Headers.ToList();
if (headers.Exists((kvp) => kvp.Key == "X-Forwarded-For"))
{
    // when running behind a load balancer you can expect this header
    var header = headers.First((kvp) => kvp.Key == "X-Forwarded-For").Value.ToString();
    // in case the IP contains a port, remove ':' and everything after
    ip = IPAddress.Parse(header.Remove(header.IndexOf(':')));
}
else
{
    // this will always have a value (running locally in development won't have the header)
    ip = Request.HttpContext.Connection.RemoteIpAddress;
}

Get Client Local IP Address

Open your Visual Studio, create a new project by navigating to File -> New -> Project -> Select "Console Application" -> Name your project and Click "Ok".

Now, to get client's local IP Address, you use the below C# code in your Program.cs

using System;
using System.Net;

namespace ClientIpAddressCsharp
{
    class Program
    {
        static void Main(string[] args)
        {
            string IPAddress = "";
            IPHostEntry Host = default(IPHostEntry);
            string Hostname = null;
            Hostname = System.Environment.MachineName;
            Host = Dns.GetHostEntry(Hostname);
            foreach (IPAddress IP in Host.AddressList)
            {
                if (IP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    IPAddress = Convert.ToString(IP);
                }
            }

            Console.WriteLine(IPAddress);
        }
    }
}

You will see output like below

client-ip-address-local-csharp-min.png

In the above code we are using System's IP Address list using IPHostEntry and looping each entry to get only InterNetwwork Ip Address.

If you will convert the above main Code in VB.NET, it will look like below

Dim Host As IPHostEntry
Dim Hostname As String
Hostname = My.Computer.Name
Host = Dns.GetHostEntry(Hostname)
For Each IP As IPAddress In Host.AddressList
    If IP.AddressFamily = System.Net.Sockets.AddressFamily.InterNetwork Then
        IPAddress = Convert.ToString(IP)
    End If
    Next
Return IPAddress

Get Public IP Address using C#

Now, to get public IP Address of we will be calling checkip.dyndns.org website, in return we will get public IP Address, but with HTML string, so we will be filtering out HTML from it, here is the complete C# Code

using System;

namespace ClientIpAddressCsharp
{
    class Program
    {
        static void Main(string[] args)
        {
            string url = "http://checkip.dyndns.org";
            System.Net.WebRequest req = System.Net.WebRequest.Create(url);
            System.Net.WebResponse resp = req.GetResponse();
            System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
            string response = sr.ReadToEnd().Trim();
            string[] ipAddressWithText = response.Split(':');
            string ipAddressWithHTMLEnd = ipAddressWithText[1].Substring(1);
            string[] ipAddress = ipAddressWithHTMLEnd.Split('<');
            string mainIP = ipAddress[0];
            Console.WriteLine(mainIP);
        }
    }
}

Ouput:

45.36.236.137 

In ASP.NET you can use below code

private string GetUserIP()
{
  string ipaddress;
  ipaddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
  if (ipaddress == "" || ipaddress == null)
      ipaddress = Request.ServerVariables["REMOTE_ADDR"];

  return ipaddress;
}

That's it, these are two easy methods to client local IP or public IP Address in C#.

You may also like to read:

In Memory cache C# (Explanation with example in .NET and .NET Core)

jQuery AJAX in ASP.NET Core MVC

How can I set JSON Serializer in ASP.NET Core (.NET 5)?

How to add a item or multiple items in C# List

Generating GUID/UUID using Javascript (Various ways)