客户端IP返回::1的解决办法

刚刚测试程序,一个功能要求获取客户端IP,然而在本机测试过程中发现,客户端(本机)IP始终返回::1,获取 IP 部份的代码如下:

 

ContractedBlock.gif ExpandedBlockStart.gif Code
    private string GetIP()
    {
        
string result = String.Empty;

        result 
= HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        
if (null == result || result == String.Empty)
        {
            result 
= HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        }

        
if (null == result || result == String.Empty)
        {
            result 
= HttpContext.Current.Request.UserHostAddress;
        }

        
if (null == result || result == String.Empty || !IsIP(result))
        {
            result 
= "0.0.0.0";
        }

        
return result;

    }

    
public static bool IsIP(string ip)
    {
        
return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
    }

 

于是最终获取倒的是因无法匹配而返回的默认IP 0.0.0.0

 google了一下,没有结果。

继续想办法。发现不影响获取其它客户端(非本机)IP。根据此现象,我想应该是localhost引起的,于是查看host映射,果然发现::1

(Host映射查看方法 C:\Windows\System32\drivers\etc  文件hosts)

 

# Copyright (c) 1993-2006 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

127.0.0.1       localhost
::1             localhost

 

原来是因为操作系统开启了IPV6,它对localhost进行了映射的原因。如果我们需要获取的IP是IPV4的,那么可以删掉::1映射。

如果将来我们需要获取的是IPV6的IP,那么就需要这样的映射。然后程序里统一实现获取IPv6的代码。

转载于:https://www.cnblogs.com/EasyLive2006/archive/2008/12/12/1353544.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值