c# get client ip address code example

Example 1: c# get pc ip address

public static string GetLocalIPAddress()
{
    var host = Dns.GetHostEntry(Dns.GetHostName());
    foreach (var ip in host.AddressList)
    {
        if (ip.AddressFamily == AddressFamily.InterNetwork)
        {
            return ip.ToString();
        }
    }
    throw new Exception("No network adapters with an IPv4 address in the system!");
}

Example 2: c# get ip address

var httpClient = new HttpClient();
var ip = await httpClient.GetStringAsync("https://api.ipify.org");
Console.WriteLine($"My public IP address is: {ip}");

Example 3: get client ip address c#

//get client ip address
Public string GetIp()
{
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"];
}
  return ip;
}