Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
3.40/5 (2 votes)
See more:
Below my code to get IP address of Client,
working correctly on IIS 6 but showing servers IP on IIS 7

tried a lot but same result
is there any setting in IIS 7 ?

C#
public static string GetIP4Address()
        {
            msgError = "";
            string IP4Address = String.Empty;
            try
            {
                foreach (IPAddress IPA in Dns.GetHostAddresses(HttpContext.Current.Request.UserHostAddress))
                {
                    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;
                    }
                }
            }
            catch (Exception ex)
            {
                
            }
            return IP4Address;
        }
Posted
Updated 1-Aug-14 2:24am
v6
Comments
HARSHADGCHAVAN 1-Aug-14 7:04am    
I am also facing the same problem ......
Hope now i will get the solution .....
Wombaticus 1-Aug-14 7:06am    
What's wrong with just Request.ServerVariables("REMOTE_ADDR") ..?
kedar001 1-Aug-14 8:20am    
thanks for the reply..
Request.ServerVariables("REMOTE_ADDR") Showing result as fe80::90da:4235:b460:3911%11
Wombaticus 1-Aug-14 9:11am    
Perhaps this will help then
http://blogs.iis.net/deanc/archive/2013/07/08/iis7-8-logging-the-real-client-ip-in-the-iis-hit-logs.aspx
Nathan Minier 1-Aug-14 9:11am    
That's an IP address, albeit IPv6.

1 solution

C#
foreach (var item in Dns.GetHostEntry(HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]).AddressList)
                {
                    if (item.AddressFamily == AddressFamily.InterNetwork)
                    {
                        IP4Address = item.ToString();
                        break;
                    }
                }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900