SoFunction
Updated on 2025-03-08

C# Example code for obtaining client IPv4 address

I found some methods to obtain client IP online, but during local testing, the representation method of IPv6 is returned "::1":

In the Host file: #    ::1             localhost

Later I found a way to get IPv4, which is easier to use:

public static string GetClientIPv4Address()
    {
      string ipv4 = ;
      foreach (IPAddress ip in (GetClientIP()))
      {
        if (() == "InterNetwork")
        {
          ipv4 = ();
          break;
        }
      }
      if (ipv4 != )
      {
        return ipv4;
      }
      //Use the method to check the DNS record from the obtained IPv6 address,      // Then determine which IPv4 protocol is one by one, and you can convert it to an IPv4 address.      foreach (IPAddress ip in (GetClientIP()).AddressList)
      //foreach (IPAddress ip in (()))
      {
        if (() == "InterNetwork")
        {
          ipv4 = ();
          break;
        }
      }
      return ipv4;
    }

    public static string GetClientIP()
    {
      if (null == ["HTTP_VIA"])
      {
        return ["REMOTE_ADDR"];
      }
      else
      {
        return ["HTTP_X_FORWARDED_FOR"];
      }
    }

The above is the detailed content of the sample code for C# to obtain the client IPv4 address. For more information about C# to obtain the IPv4 address, please follow my other related articles!