c# get ip address of client

Get IP Address of client in ASP.Net C#

Hello everyone, I am going to share the code-sample for Get IP Address of client machine using the ASP.Net C#.

Table of Context :-
1.      Examples 1 for GET IP Address.
2.      Examples 1 for GET IP Address.

Both the example code as below

Example 1,
public static string GetLocalIPAddress()
    var host = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
    foreach (var ip in host.AddressList)
        if (ip.AddressFamily == AddressFamily.InterNetwork)
            return ip.ToString();
    throw new Exception("Local IP Address Not Found!");

Example 2,
public string GetIPAddress()
    HttpContext httpContext = HttpContext.Current;
    string currentIPAddress = httpContext.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

    if (!string.IsNullOrEmpty(currentIPAddress))
        string[] ipAddresses = currentIPAddress.Split(',');
        if (ipAddresses.Length != 0)
            return ipAddresses[0];
    return httpContext.Request.ServerVariables["REMOTE_ADDR"];


Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

Get IP Address of client in ASP.Net C# Get IP Address of client in ASP.Net C# Reviewed by Anil Singh on 11:09 PM Rating: (5)
www.code-sample.com/. Powered by Blogger.