Why am I getting ::1 as IP address in ASP.Net.. and how to get the proper IP address?

雨燕双飞 提交于 2019-11-29 05:44:19

You are getting a valid IP Address. ::1 is local_host in IPv6. (underscore used in local_host to stop SO from thinking it was some sort of bad text)

What you're seeing when calling 'localhost' is valid. ::1 is the IPv6 loopback address. Equivalent to 127.0.0.1 for IPv4.

Instead of calling:

 http://localhost/...

Call:

 http://{machinename}/...
        -or-
 http://127.0.0.1/...
        -or- 
 http://192.168.1.XXX/...

[Replace {machinename} with your machine's computer name. Replace XXX with your computers IP address.]

Anyone calling into your machine to the MVC app will have there valid IP address as a result. If the client is a IPv6 host it will save there IPv6 IP address. If the client is a IPv4 host it will save there IPv4 IP address.

If you always want to save a IPv4 address take a look at this article on how they accomplished it with a simple class http://www.4guysfromrolla.com/articles/071807-1.aspx. You should be able to take there example and build a quick helper method to accomplish this.

Request.Params["REMOTE_ADDR"]

instead of Request.ServerVariables("REMOTE_ADDR")

If you want localhost return 127.0.0.1, maybe you need to change your "hosts" file. You can find it in "%systemdrive%\Windows\System32\drivers\etc"

It works for me, now I get 127.0.0.1 with "Request.ServerVariables["REMOTE_ADDR"]". I uncomment 127.0.0.1 (remove #).

Here you can find default hosts file http://support.microsoft.com/kb/972034

My file

# localhost name resolution is handled within DNS itself.

127.0.0.1       localhost

# ::1 localhost

below code i have used for finding ip

public static string GetIp()
        {
            var Request = HttpContext.Current.Request;

            try
            {

                Console.WriteLine(string.Join("|", new List<object> {
                    Request.UserHostAddress,
                    Request.Headers["X-Forwarded-For"],
                    Request.Headers["REMOTE_ADDR"]
                })
                );

                var ip = Request.UserHostAddress;
                if (Request.Headers["X-Forwarded-For"] != null)
                {
                    ip = Request.Headers["X-Forwarded-For"];
                    Console.WriteLine(ip + "|X-Forwarded-For");
                }
                else if (Request.Headers["REMOTE_ADDR"] != null)
                {
                    ip = Request.Headers["REMOTE_ADDR"];
                    Console.WriteLine(ip + "|REMOTE_ADDR");
                }
                return ip;
            }
            catch (Exception ex)
            {
                Log.WriteInfo("Message :" + ex.Message + "<br/>" + Environment.NewLine +
                    "StackTrace :" + ex.StackTrace);
            }
            return null;
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!