C # get Web client IP

Source: Internet
Author: User

#region Get the Web client IP

<summary>
Get IP Address
</summary>
<returns></returns>
public static string Getipaddress ()
{
string IPv4 = String.Empty;
foreach (IPAddress IP in dns.gethostaddresses (Getclientip ()))
{
if (IP. addressfamily.tostring () = = "Internetwork")
{
IPv4 = IP. ToString ();
Break
}
}
if (IPv4! = String.Empty)
{
return IPv4;
}
Using the Dns.gethostentry method, the Dns records are retrieved from the obtained IPV6 address,
One by one to determine which is the IPV4 protocol, can be converted to IPV4 address.
foreach (IPAddress IP in Dns.gethostentry (Getclientip ()). AddressList)
foreach (IPAddress IP in dns.gethostaddresses (Dns.gethostname ()))
{
if (IP. addressfamily.tostring () = = "Internetwork")
{
IPv4 = IP. ToString ();
Break
}
}
return IPv4;
}

 private static string Getclientip ()
        {
             if (null = = httpcontext.current.request.servervariables["Http_via "])
            {
                 return httpcontext.current.request.servervariables[ "REMOTE_ADDR"];
           }
            Else
             {
                 return httpcontext.current.request.servervariables["Http_x_forwarded_for"];
           }
       } 

#endregion

C # get Web client IP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.