Wednesday, October 12, 2011

C# / ASP.NET - Getting an IP Address

If you are attempting to get an IP address, from a system connected to your ASP.NET page, or just trying to pull up a local IP address, the following code block can be used. The GetHostAddresses method queries a DNS server for the IP addresses associated with a host name. If the system has IPV6 enabled, and you are trying to pull the IP address, simply using GetHostAddresses won't work, as it will return the IPV6 address. This code should generate your IPV4 address.
// using System.Net; (Required)
 
protected string GetIPAddress()
{
     string IPV4Address = String.Empty;
 
     foreach (IPAddress IPAddr in 
        Dns.GetHostAddresses(HttpContext.Current.Request.UserHostAddress))
     {
          if (IPAddr.AddressFamily.ToString() == "InterNetwork")
          {
               IPV4Address = IPAddr.ToString();
               break;
          }
     }
 
     if (IPV4Address != String.Empty)
         return IPV4Address;
 
     foreach (IPAddress IPAddr in Dns.GetHostAddresses(Dns.GetHostName()))
     {
         if (IPAddr.AddressFamily.ToString() == "InterNetwork")
         {
              IPV4Address = IPAddr.ToString();
              break;
         }
     }
 
     return IPV4Address;
}
Post a Comment