title: Get Web Api consumer IP Address and HostName in ASP.NET Web API
body: <p>I have hosted Web Api developed in ASP.net. I want if someone call my API so I can log in database so later on if I want to reject request from particular id using C#. </p>
  
  <p>What is best practice to get consumer IP and HostName?</p>
  
  <pre><code>public static string GetIP4Address()
    {
      string IP4Address = String.Empty;
  
      foreach (IPAddress IPA in Dns.GetHostAddresses(Request.ServerVariables["REMOTE_ADDR"].ToString())))
      {
        if (IPA.AddressFamily.ToString() == "InterNetwork")
        {
          IP4Address = IPA.ToString();
          break;
        }
      }
  
      if (IP4Address != String.Empty)
      {
        return IP4Address;
      }
  
      foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
      {
        if (IPA.AddressFamily.ToString() == "InterNetwork")
        {
          IP4Address = IPA.ToString();
          break;
        }
      }
  
      return IP4Address;
    }
  </code></pre>