如何在ASP.NET中识别用户是在我的网络内部还是外部

本文关键字:我的 网络 外部 内部 识别 ASP NET 用户 | 更新日期: 2023-09-27 18:25:17

我必须确定访问是从我的本地网络(我的服务器的同一网络)混合还是从互联网混合。(使用ASP.NET)

我正计划建立一个额外的安全机制。。我的意思是,如果访问是从外部混合的,我将只"允许"特定的用户。

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

提前谢谢。

如何在ASP.NET中识别用户是在我的网络内部还是外部

您可以执行类似的操作(伪代码)

  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");

和CCD_ 2方法

 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;
        }