title: How to Get system IP (IPv4) address and convert to string using C# asp.net
body: <p>On my web application I am using the following function to get System IP </p>
  
  <p><strong>Function</strong></p>
  
  <pre><code>public void SetHostid()
      {
          try
          {
              string ip = "";
              string strHostName = "";
              strHostName = System.Net.Dns.GetHostName();
  
              IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
  
              IPAddress[] addr = ipEntry.AddressList;
  
              ip = addr[1].MapToIPv4().ToString();
  
              HostId = ip;
              HttpContext.Current.Session["Hostid"] = HostId;
          }
          catch (Exception ex)
          {
              Error_ManagerClass em = new Error_ManagerClass();
              em.WriteError(ex);
          }
      }
  </code></pre>
  
  <p>It works perfectly because the IP is on the 1 postion of the variable addr (<code>addr[ 1]</code>).
  <a href="https://i.stack.imgur.com/oFGsN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oFGsN.png" alt="enter image description here"></a></p>
  
  <p>And the problem comes when I try to run the same solution from a different system. function throws an error while trynig to convert IP to string(  <code>ip = addr[1].MapToIPv4().ToString();</code> ) because IP is not in the position number 1.<br><a href="https://i.stack.imgur.com/8qKC1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8qKC1.png" alt="enter image description here"></a></p>
  
  <p>how can I change the function to work on every computer ?? </p>