【问题标题】:How to identify if user is inside or outside my network in ASP.NET如何在 ASP.NET 中识别用户是在我的网络内部还是外部
【发布时间】:2013-07-29 23:21:11
【问题描述】:

我必须确定访问是来自我的本地网络(与我的服务器相同的网络)还是来自互联网。 (使用 ASP.NET)

我计划创建一个额外的安全性。我的意思是,如果访问来自外部,我将只“允许”特定用户。

我尝试在网上搜索,但一无所获。

提前致谢。

【问题讨论】:

  • “我的服务器的同一个网络”是非常主观的,具体取决于您的网络布局。 10.50.0.84 和 10.110.48.22 是同一个网络吗?这些 IP 地址会改变吗?来自 Internet 的流量是如何到达您的服务器的(混合中是否有反向代理?是否存在外部身份验证?)这些只是我想到的一些问题。我认为您需要先讨论细化需求,然后再提出解决方案。

标签: c# asp.net security


【解决方案1】:

你可以做这样的事情(虚拟代码)

  private bool IsInSameSubnet(IPAddress address, IPAddress address2, IPAddress subnetMask) {
            bool isInSameSubnet = false;
            IPAddress network1 = GetNetworkAddress(address, subnetMask);
            IPAddress network2 = GetNetworkAddress(address2, subnetMask);
            if (network1 != null && network2 != null) {
                isInSameSubnet = network1.Equals(network2);
            }
            return isInSameSubnet;
        }
    private IPAddress GetNetworkAddress(IPAddress address, IPAddress subnetMask) {

        byte[] ipAdressBytes = address.GetAddressBytes();
        byte[] subnetMaskBytes = subnetMask.GetAddressBytes();

        if (ipAdressBytes.Length != subnetMaskBytes.Length)
            return null;
        //throw new ArgumentException("Lengths of IP address and subnet mask do not match.");

        byte[] broadcastAddress = new byte[ipAdressBytes.Length];
        for (int i = 0; i < broadcastAddress.Length; i++) {
            broadcastAddress[i] = (byte)(ipAdressBytes[i] & (subnetMaskBytes[i]));
        }
        return new IPAddress(broadcastAddress);
    }

IsInSameSubnet 地址检查是否在同一个网络中

示例:

string computerIP = getIP();

            IPAddress ip1 = IPAddress.Parse(computerIP);
            IPAddress ip2 = IPAddress.Parse("192.168.0.0");
            IPAddress subnetMask = IPAddress.Parse("255.255.0.0");

getIp 方法

 public static string getIP() {
            //if user behind proxy this should get it
            string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (ip != null && ip.Split(',').Count() > 1) {
                //if (ip.Split(',').Count() > 1)
                ip = ip.Split(',')[0];
            }

            //if user not behind proxy this should do it
            if (ip == null)
                ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            return ip;
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-30
    • 2011-12-20
    • 1970-01-01
    • 2022-12-17
    • 2016-01-19
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    相关资源
    最近更新 更多